Skip to main content

Javascript Syntax

JavaScript syntax is the set of rules that dictate how JavaScript code should be written. Following these rules ensures that the code is valid and can be executed correctly.

Below are some important syntax rules that should be followed while writing JavaScript code:

Statements

Each line of JavaScript code is a statement, and statements should end with a semicolon (;). While not always required, it's a good practice to include semicolons to avoid potential issues with automatic semicolon insertion.

let firstName = "John";
let lastName = "Doe";
console.log(firstName + " " + lastName);

Comments

Use // to insert single-line comments or /\* \*/ to insert multi-line comments. Comments are ignored by the JavaScript interpreter and are used to add explanatory notes to the code.

// This is a single-line comment

/*
This is a
multi-line
comment
*/

Variables

Variables in JavaScript are declared using the var, let, or const keywords. The variable name should follow the keyword and should not contain any spaces or special characters.

let age = 30;
const pi = 3.14;
var message = "Hello, World!";

Data Types

JavaScript has several data types, including strings, numbers, booleans, and objects. It's important to use the correct data type for each variable and to be aware of type coercion "Reference", which can cause unexpected behavior.

let name = "John";
let age = 30;
let isMarried = true;
let fruits = ["apple", "banana", "orange"];
let person = {
name: "John",
age: 30,
isMarried: true,
};

Operators

JavaScript has a variety of operators, including arithmetic, assignment, comparison, and logical operators.

It is important to use the correct operator for the task at hand.

let x = 10;
let y = 5;
let sum = x + y; // addition
let product = x * y; // multiplication
let isEqual = x === y; // strict equality comparison
let isNotEqual = x !== y; // strict inequality comparison
let isGreater = x > y; // greater than comparison
let isLess = x < y; // less than comparison

Functions

Functions in JavaScript are declared using the function keyword, followed by the function name, input parameters (if any), and the function body.

Functions can be called with or without arguments and can return a value or modify the program state.

function greet(name) {
console.log("Hello, " + name + "!");
}

function add(x, y) {
return x + y;
}

let result = add(2, 3); // result is 5

Conditional Statements

JavaScript has several conditional statements, including if, else if, and else. These statements are used to execute different code blocks based on a condition.

let x = 10;
let y = 5;

if (x > y) {
console.log("x is greater than y");
} else if (x < y) {
console.log("x is less than y");
} else {
console.log("x is equal to y");
}

Loops

JavaScript has several types of loops, including for, while, and do...while. These loops are used to repeat code blocks until a certain condition is met.

let i;

for (i = 0; i < 5; i++) {
console.log(i);
}

let j = 0;

while (j < 5) {
console.log(j);
j++;
}

let k = 0;

do {
console.log(k);
k++;
} while (k < 5);

JavaScript Values

JavaScript values are the data that JavaScript programs manipulate.

Some common types of JavaScript values include:

  • Numbers: Numeric values in JavaScript, such as 5, 3.14, or -10.

  • Strings: Textual values in JavaScript, such as "Hello, World!", "123", or "true".

  • Booleans: Logical values that can be either true or false.

  • Null: A special value that represents the absence of any object value.

  • Undefined: A special value that represents a variable that has been declared but not assigned a value.

  • Objects: Complex values that can hold multiple values, such as arrays, functions, and custom objects.

  • Arrays: A type of object that stores a collection of values in a list format.

  • Functions: A type of object that can be called with or without arguments to perform a specific task.

Few examples of JavaScript values:

let age = 30; // a number value
let name = "John"; // a string value
let isMarried = true; // a boolean value
let myArray = [1, 2, 3]; // an array value
let myObject = {firstName: "John", lastName: "Doe"}; // an object value
let myFunction = function (x, y) {
return x + y;
}; // a function value
let nullValue = null; // a null value
let undefinedValue; // an undefined value

JavaScript Literals

In JavaScript, a literal is a value that is written directly in the code, rather than being stored in a variable or computed by an expression.

Here are some examples of JavaScript literals:

  • Numeric literals: Numeric values written directly in the code, such as 10, 3.14, or -5.

  • String literals: Textual values written directly in the code, such as "Hello, World!" or 'JavaScript'.

  • Boolean literals: Logical values written directly in the code, such as true or false.

  • Object literals: Values that define objects directly in the code, such as {name: "John", age: 30}.

  • Array literals: Values that define arrays directly in the code, such as [1, 2, 3].

  • Regular expression literals: Values that define regular expressions directly in the code, such as /^[A-Z]/.

Examples of JavaScript literals:

let numberLiteral = 10;
let stringLiteral = "Hello, World!";
let booleanLiteral = true;
let objectLiteral = {name: "John", age: 30};
let arrayLiteral = [1, 2, 3];
let regexLiteral = /^[A-Z]/;

JavaScript is Case Sensitive

JavaScript is a case-sensitive language. This means that variables, functions, and other identifiers in JavaScript must be spelled and capitalized consistently throughout your code.

As an example

  • The variables firstName and firstname are considered two different variables in JavaScript.
  • Similarly, the functions myFunction and myfunction are also considered two different functions.

Example to understand case sensitivity:

let firstName = "John";
let FirstName = "Doe";

console.log(firstName); // "John"
console.log(FirstName); // "Doe"

Explanation:

  • firstName and FirstName are two different variables with different capitalizations.

  • If we were to write console.log(firstname) instead of console.log(firstName), we would get an error because firstname is not defined.

TIP - Using Capitalization

It's important to be consistent with your capitalization in JavaScript to avoid errors and make your code easier to read and understand.

JavaScript and Camel Case

In the context of JavaScript, camel case is a convention used to name variables, functions, and other identifiers. Camel case is a naming convention where the first word is lowercase, and the first letter of each subsequent word is capitalized, without spaces.

As an example, firstName, myVariable, and calculateAge are all examples of identifiers in camel case.

Guidelines for using camelCase

Some recommended guidelines for using camelCase in JavaScript:

  • Always start with a lowercase letter: Variables and functions should always start with a lowercase letter in camel case. This helps distinguish them from constructor functions, which typically start with a capital letter.

  • Use meaningful names: Your variable and function names should describe what they do or what values they hold. This makes your code more readable and understandable.

  • Be consistent: Be consistent with your use of camel case throughout your code. If you start with lowercase for your variables, stick to that convention.

Examples of camel case:

let firstName = "John";
let lastName = "Doe";

function calculateAge(birthYear) {
let currentYear = new Date().getFullYear();
let age = currentYear - birthYear;
return age;
}
note

Using camel case as a convention in your code can enhance its readability, leading to time savings and reduced likelihood of errors.

JavaScript Character Set

JavaScript adopts Unicode, a universal character encoding system that assigns unique numbers to all characters and symbols used in written languages.

Unicode supports over 140,000 characters, including mathematical symbols, emojis, and most writing systems worldwide.

JavaScript supports all Unicode characters, such as letters, digits, punctuation, and symbols. It enables coding in any language using Unicode characters, as long as text editors and browsers support them.

Examples of Unicode characters:

let π = 3.14159; // Greek letter pi
let こんにちは = "Hello"; // Japanese greeting
let 💻 = "computer"; // computer emoji
note

It is recommended to use easily readable characters that have broad support in browsers and text editors. Stick to ASCII for common characters and only turn to Unicode when necessary.