ES6 - Syntax
ES6 - Syntax Fundamentals
Section titled “ES6 - Syntax Fundamentals”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.
Core Components of a JavaScript Program
Section titled “Core Components of a JavaScript Program”- 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+), orvar(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 (myVaris different fromMyVar). - 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 */
Key JavaScript Keywords (ES6+ Focus):
Section titled “Key JavaScript Keywords (ES6+ Focus):”The following table lists some commonly used keywords in modern JavaScript:
| Keywords Set 1 | Keywords Set 2 | Keywords Set 3 | Keywords Set 4 |
|---|---|---|---|
async | await | break | case |
catch | class | const | continue |
debugger | default | delete | do |
else | export | extends | false |
finally | for | function | if |
import | in | instanceof | let |
new | null | return | super |
switch | this | throw | true |
try | typeof | var (legacy) | void |
while | with (discouraged) | yield | static (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.
Valid vs. Invalid Identifiers:
Section titled “Valid vs. Invalid Identifiers:”| Examples of Valid Identifiers | Examples of Invalid Identifiers |
|---|---|
firstName_value$amountuser1calculateTotal | 1stName (cannot start with a digit)my-variable (hyphens not allowed)let (keyword)first name (spaces not allowed) |
Whitespace and Line Breaks
Section titled “Whitespace and Line Breaks”JavaScript largely ignores spaces, tabs, and newlines between tokens. This allows for flexible code formatting and indentation, which is crucial for readability.
Case Sensitivity
Section titled “Case Sensitivity”JavaScript is case-sensitive. This means myVariable, MyVariable, and myvariable would be treated as three distinct identifiers.
Semicolons
Section titled “Semicolons”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.
Example:
Section titled “Example:”console.log("Hello ES6"); // Semicolon presentconsole.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:
const message = "Hello, ES6 World!";console.log(message);- Line 1: Declares a constant variable named
messageand initializes it with the string “Hello, ES6 World!”.constmeans this variable cannot be reassigned. - Line 2:
console.log()is a built-in function that prints the value ofmessageto the console (e.g., browser developer console or Node.js terminal).
Executing the Code (e.g., with Node.js):
Section titled “Executing the Code (e.g., with Node.js):”- 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.jsand press Enter.
Output:Hello, ES6 World!Strict Mode ("use strict";)
Section titled “Strict Mode ("use strict";)”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 in JavaScript
Section titled “Hoisting in JavaScript”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.
vardeclarations: Hoisted and initialized withundefined.letandconstdeclarations: Hoisted but not initialized. Accessing them before their declaration in the code results in aReferenceError(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() {}orconst foo = () => {}): Only the variable declaration part is hoisted (likevar,let, orconst). The function body assignment is not hoisted, so they cannot be called before assignment.
Example: Hoisting with var vs. let
Section titled “Example: Hoisting with var vs. let”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;Example: Function Hoisting
Section titled “Example: Function Hoisting”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.