Skip to main content

Basic Syntax

Getting Started with JavaScript: Basic Syntax

JavaScript is a popular, high-level, dynamic, interpreted programming language that is widely used for making web pages interactive. It is an integral part of modern web browsers and provides many essential features that make the web what it is today. In this tutorial, we will be covering some of the basic syntax of JavaScript to get you started.

JavaScript Statements

In JavaScript, statements are instructions that are executed by the web browser. Each statement is started on a new line and is separated by a semicolon (;), much like sentences in English.

Here is an example:

var x = 5; // This is a JavaScript statement

Variables

Variables are used to store data. In JavaScript, you declare a variable using the var keyword. Following is an example of how to declare a variable:

var name; // Declaring a variable

You can also assign a value to a variable when you declare it:

var name = 'John'; // Declaring a variable and assigning a value to it

Data Types

JavaScript has several types of data that can be stored in variables. These include:

  • Number: Represents numeric values. Example: var num = 25;
  • String: Represents a sequence of characters. Example: var str = 'Hello World';
  • Boolean: Represents logical values true or false. Example: var isTrue = true;
  • Object: Represents complex data structures. Example: var person = {firstName:"John", lastName:"Doe"};
  • Undefined: Represents a variable that has not been assigned a value. Example: var x;
  • Null: Represents a null or "nothing" value. Example: var x = null;

Operators

Operators are used to perform operations on variables and values. JavaScript includes arithmetic operators such as +, -, *, /, and %, comparison operators such as ==, ===, !=, !==, <, >, <=, and >=, and logical operators such as &&, ||, and !.

Here are some examples:

var a = 10;
var b = 20;
var c = a + b; // c will be 30

Control Structures

Control structures control the flow of the code. They include if...else statements, switch statements, and loops (for, while, do...while).

Here is an example of an if...else statement:

var a = 10;
if (a < 20) {
console.log('a is less than 20');
} else {
console.log('a is not less than 20');
}

Functions

Functions are blocks of reusable code that perform a particular task. Functions are defined using the function keyword.

Here is an example of a function:

function greet() {
console.log('Hello, World!');
}

// Call the function
greet();

In this tutorial, we have covered the very basics of JavaScript syntax. JavaScript is a vast language with many more concepts to explore. Keep practicing and experimenting with these basics, and soon you will be ready to delve deeper into the world of JavaScript. Happy coding!