Skip to content

ES6 - Syntax

JavaScript syntax defines the set of rules for writing programs that the JavaScript engine can understand and execute. Understanding these fundamentals is crucial for writing effective code.

  • Literals: Fixed values written directly in the code. Examples: 100 (number), "Hello ES6" (string), true (boolean), null, [1, 2, 3] (array), { name: "Alice" } (object).
  • Variables: Named storage locations for data. Declared using let, const (ES6+), or var (older).
  • Operators: Symbols that perform operations on operands (values or variables). Examples: +, -, *, /, =, ===, &&, ||.
  • Keywords: Reserved words with special meanings in JavaScript. Examples: if, else, for, while, function, class, return, let, const, import, export.
  • Identifiers: Names given to variables, functions, classes, etc. They must follow specific rules: - Start with a letter, underscore (_), or dollar sign ($). - Subsequent characters can also be digits. - Case-sensitive (myVar is different from MyVar). - Cannot be a reserved keyword.
  • Statements: Instructions to be executed by the JavaScript engine, typically ending with a semicolon (;).
  • Expressions: Any valid unit of code that resolves to a value (e.g., x + y, myFunction(), 3 * 7).
  • Comments: Notes in the code ignored by the interpreter, used for explanation. - Single-line: // This is a comment - Multi-line: /* This is a multi-line comment */

The following table lists some commonly used keywords in modern JavaScript:

Keywords Set 1Keywords Set 2Keywords Set 3Keywords Set 4
asyncawaitbreakcase
catchclassconstcontinue
debuggerdefaultdeletedo
elseexportextendsfalse
finallyforfunctionif
importininstanceoflet
newnullreturnsuper
switchthisthrowtrue
trytypeofvar (legacy)void
whilewith (discouraged)yieldstatic (in classes)

Note: Some words like enum, implements, interface, package, private, protected, public are reserved for future use and should not be used as identifiers.

Examples of Valid IdentifiersExamples of Invalid Identifiers
firstName
_value
$amount
user1
calculateTotal
1stName (cannot start with a digit)
my-variable (hyphens not allowed)
let (keyword)
first name (spaces not allowed)

JavaScript largely ignores spaces, tabs, and newlines between tokens. This allows for flexible code formatting and indentation, which is crucial for readability.

JavaScript is case-sensitive. This means myVariable, MyVariable, and myvariable would be treated as three distinct identifiers.

Semicolons (;) are used to terminate statements. While JavaScript has Automatic Semicolon Insertion (ASI), which attempts to insert semicolons where they seem to be missing, relying on ASI can lead to subtle bugs. It is a widely accepted best practice to explicitly include semicolons at the end of each statement.

console.log("Hello ES6"); // Semicolon present
console.log("We are learning modern JavaScript"); // Semicolon present
// Multiple statements on one line require semicolons to separate them:
let x = 5; let y = 10; console.log(x + y);

Your First JavaScript Code (Modern Approach)

Section titled “Your First JavaScript Code (Modern Approach)”

Let’s look at a simple “Hello World” example using modern practices:

main.js
const message = "Hello, ES6 World!";
console.log(message);
  • Line 1: Declares a constant variable named message and initializes it with the string “Hello, ES6 World!”. const means this variable cannot be reassigned.
  • Line 2: console.log() is a built-in function that prints the value of message to the console (e.g., browser developer console or Node.js terminal).
  • Save the code in a file named main.js.
  • Open your terminal or command prompt.
  • Navigate to the directory where you saved the file.
  • Type node main.js and press Enter.
Output:
Hello, ES6 World!

Strict Mode is a way to opt into a restricted variant of JavaScript. It helps catch common coding mistakes and prevents or throws errors for certain “unsafe” actions. It’s highly recommended for new projects.

To enable strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) at the very beginning of the script.

"use strict";
// In strict mode, assigning to an undeclared variable throws an error:
// undeclaredVar = "This would be an error.";
let declaredVar = "This is fine.";
console.log(declaredVar);

It can also be applied to individual functions:

function myStrictFunction() {
"use strict";
// anUndeclaredVariable = "Error inside this function";
let anotherVar = "Also fine inside function";
console.log(anotherVar);
}
myStrictFunction();

Important Note: ES6 Modules (import/export syntax) are automatically in strict mode. You don’t need to add "use strict"; at the top of a module file.

Hoisting is JavaScript’s default behavior of moving declarations to the top of their current scope (script scope for global variables/functions, or function scope for local variables/functions) before code execution. However, initializations are not hoisted.

  • var declarations: Hoisted and initialized with undefined.
  • let and const declarations: Hoisted but not initialized. Accessing them before their declaration in the code results in a ReferenceError (this is known as the Temporal Dead Zone - TDZ).
  • Function declarations (function foo() {}): Hoisted entirely (name and body). They can be called before they appear in the code.
  • Function expressions (const foo = function() {} or const foo = () => {}): Only the variable declaration part is hoisted (like var, let, or const). The function body assignment is not hoisted, so they cannot be called before assignment.
console.log(x); // undefined (var x is hoisted and initialized with undefined)
var x = 5;
// console.log(y); // ReferenceError: Cannot access 'y' before initialization (let y is hoisted but in TDZ)
// let y = 10;
sayHello(); // Works: "Hello from declared function!"
function sayHello() {
console.log("Hello from declared function!");
}
// sayGoodbye(); // TypeError: sayGoodbye is not a function (if var) or ReferenceError (if let/const)
// const sayGoodbye = () => {
// console.log("Goodbye from arrow function!");
// };

Understanding hoisting and the TDZ for let/const is important for avoiding common errors. Generally, it’s good practice to declare variables and functions before using them to improve code clarity.