Skip to content

Chapter 2 of 8

Variables, Types, and Operators

JavaScript offers three keywords for declaring variables: var, which is function-scoped, and let and const, both of which are block-scoped and were introduced in ES6. const declares a binding that cannot be reassigned, while let allows reassignment within its block. The language has seven primitive data types: string, number, bigint, boolean, undefined, null, and symbol. Primitives are immutable values, and you can identify a value's type with the typeof operator, which returns a string such as 'string' when given 'hello'.

A frequent source of confusion is the difference between null and undefined. null represents an intentional absence of a value, whereas undefined means a variable has been declared but not yet assigned. Interestingly, typeof null returns 'object', a long-standing historical bug in the language. JavaScript also performs automatic type coercion, converting values between types in operations such as '5' + 1, which yields the string '51'. To avoid surprises from coercion, developers are encouraged to use === for strict equality instead of ==, because === compares both value and type without converting them.

JavaScript provides the usual arithmetic operators—+, -, *, /, % (modulus), and ** (exponentiation)—all of which work on numbers. Comparison operators such as ==, ===, !=, !==, and the relational operators all return a boolean (true or false). Logical operators && (AND), || (OR), and ! (NOT) perform boolean logic and enable short-circuit evaluation, which is the basis for idiomatic patterns such as value && doSomething().

All chapters
  1. 1JavaScript Foundations
  2. 2Variables, Types, and Operators
  3. 3Control Flow and Functions
  4. 4Data Structures and ES6 Syntax
  5. 5Scope, Hoisting, and Closures
  6. 6Objects, Classes, and Built-in APIs
  7. 7Asynchronous JavaScript
  8. 8Browser Interaction and Best Practices

Drill it

Reading is not remembering. These come from the Javascript Fundamentals deck:

Q

What is JavaScript?

JavaScript is a high-level, interpreted programming language primarily used for web development to make web pages interactive. It is the scripting language of t...

Q

Who created JavaScript and in what year?

JavaScript was created by Brendan Eich in 1995 while working at Netscape. It was initially called Mocha, then LiveScript, before being renamed JavaScript.

Q

What is ECMAScript?

ECMAScript (ES) is the standardized scripting language specification upon which JavaScript is based. The latest stable version is ES2023, with JavaScript implem...

Q

How do you include JavaScript in an HTML file?

Use the <script> tag in the HTML, either inline with code between tags or externally via <script src="script.js"></script>. Place it before th...