0
0
JavascriptHow-ToBeginner · 3 min read

How to Use console.warn in JavaScript: Syntax and Examples

Use console.warn() in JavaScript to display warning messages in the browser console. Pass the message as a string or multiple values inside the parentheses, like console.warn('Warning message').
📐

Syntax

The console.warn() method prints a warning message to the browser console. It accepts one or more arguments, which can be strings, variables, or expressions.

  • console.warn(message): Displays the warning message.
  • message: The text or data you want to show as a warning.
javascript
console.warn('This is a warning message');
Output
Warning: This is a warning message
💻

Example

This example shows how to use console.warn() to alert about a potential issue in your code. The message appears in the console with a warning icon.

javascript
function checkAge(age) {
  if (age < 18) {
    console.warn('User is under 18 years old');
  } else {
    console.log('User is an adult');
  }
}

checkAge(15);
checkAge(21);
Output
Warning: User is under 18 years old User is an adult
⚠️

Common Pitfalls

Common mistakes when using console.warn() include:

  • Forgetting to pass a message, which results in an empty warning.
  • Using console.warn without parentheses, which does not call the function.
  • Confusing console.warn() with console.error() or console.log()—each has a different purpose and style.
javascript
/* Wrong: Missing parentheses, no function call */
console.warn('This will cause an error');

/* Correct: Proper function call with parentheses */
console.warn('This is a proper warning');
📊

Quick Reference

UsageDescription
console.warn(message)Prints a warning message to the console
console.warn()No message prints an empty warning
console.warn(variable)Prints the value of a variable as a warning
console.warn('Warning:', variable)Prints multiple values in one warning message

Key Takeaways

Use console.warn() to show warning messages clearly in the browser console.
Always include parentheses and pass a message to avoid errors or empty warnings.
console.warn() helps highlight potential issues without stopping code execution.
It accepts multiple arguments, allowing flexible warning messages.
Differentiate console.warn() from console.error() and console.log() for proper message types.