JavaScript Syntax
JavaScript code is made up of statements, which are like sentences. They are executed one by one. A common practice is to end each statement with a semicolon (;), although it's often optional thanks to JavaScript's Automatic Semicolon Insertion (ASI).
JavaScript
let message = "Hello, world!"; // This is one statement. console.log(message); // This is another statement.
Variables: Storing Data
A variable is a container for a value. Think of it as a labeled box where you can store information. In modern JavaScript, we have two main ways to declare variables: let and const.
- let: Use let when you expect the variable's value to change later.
JS
let score = 100; console.log(score); // 100 score = 150; // The value can be updated. console.log(score); // 150
- const: Use const (short for constant) when the value should never change. Attempting to change it will result in an error. This is great for making your code safer and more predictable.
const birthYear = 1995; // birthYear = 1996; // This would cause a TypeError!
- var: You will see var in older code. It's the original way to declare variables. It has some quirky scoping rules that can cause bugs, so the modern best practice is to always prefer let and const.
Data Types
JavaScript variables can hold different types of data. These are the main primitive data types:
- String: Textual data, enclosed in single (') or double (") quotes.
const name = "Alice";
- Number: Both integers and floating-point numbers.
const age = 30; const price = 19.99;
- Boolean: Represents a logical value of true or false.
const isLoggedIn = true;
- Undefined: A variable that has been declared but not yet assigned a value has the value undefined.
let userRole; console.log(userRole); // undefined
- Null: Represents the intentional absence of any object value. It's a value you can assign yourself.
let selectedProduct = null;
- Symbol and BigInt are newer, more specialized primitive types.
JavaScript is a dynamically typed language, meaning you don't have to specify the data type of a variable. The same variable can even hold different types over time (though this is often a bad practice).
JavaScript
let myVar = "I am a string"; console.log(typeof myVar); // "string" myVar = 101; console.log(typeof myVar); // "number"