JavaScript Expressions

By

Learn what JavaScript expressions are and how literals, operators, assignments, property access, function calls, and object creation produce values.

~~~

An expression is a piece of JavaScript code that produces a value.

For example, all these lines are expressions:

42
'Hello'
2 + 3
user.name

JavaScript evaluates each one and gives us a value back.

Literals and identifiers

A literal writes a value directly in the code:

10
'Flavio'
true
[1, 2, 3]

An identifier is the name of a variable, function, or other value:

user
total

Reading the identifier is also an expression because it produces its current value.

Expressions with operators

Operators combine expressions into a new expression:

2 + 3
price * quantity
age >= 18
isLoggedIn && isAdmin

Comparison expressions return true or false.

The && and || operators return one of their operands, which is not always a boolean.

Assignment expressions

An assignment stores a value and also produces that value:

let total = 0
total = 10
total += 5

This is why an assignment can appear inside a larger expression, although keeping it on its own line is usually clearer.

Property access and function calls

Accessing a property produces its value:

user.name
user['name']

Calling a function is an expression too. Its value is whatever the function returns:

Math.max(2, 5)
name.toUpperCase()

Creating an object with new is another expression:

new Date()
new URL('https://flaviocopes.com')

Function and class expressions

Functions and classes can be expressions when we use them where JavaScript expects a value:

const double = function(number) {
  return number * 2
}

const User = class {
  constructor(name) {
    this.name = name
  }
}

This is different from a statement such as if, for, or a function declaration. A statement performs an action but does not produce a value that we can use in another expression.

Tagged: JavaScript ยท All topics
~~~

Related posts about js: