The Wayback Machine - https://web.archive.org/web/20241115134801/https://www.geeksforgeeks.org/javascript-basic-syntax/
Open In App

JavaScript Syntax

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.

Syntax

console.log("Basic Print method in JavaScript");

JavaScript syntax refers to the set of rules that determines how JavaScript programs are constructed:

// Variable declaration
let c, d, e;

// Assign value to the variable
c = 5; 

// Computer value of variables
d = c;
e = c / d;

JavaScript Values

There are two types of values defined in JavaScript Syntax:

  • Fixed Values: These are known as the literals.
  • Variable values: These are called variables

These are the features of JavaScript which have some predefined syntax:

JavaScript Literals

Syntax Rules for the JavaScript fixed values are:

  • JavaScript Numbers can be written with or without decimals.
  • Javascript Strings are text that can be written in single or double quotes.
JavaScript
let num1 = 50
let num2 = 50.05

let str1 = "Geek"
let str2 = 'Geeks'

console.log(num1)
console.log(num2)
console.log(str1)
console.log(str2)

Output
50
50.05
Geek
Geeks

JavaScript Variables

A JavaScript variable is the simple name of the storage location where data is stored. There are two types of variables in JavaScript which are listed below: 

Example: This example shows the use of JavaScript variables.

JavaScript
// Declare a variable and initialize it
// Global variable declaration
let Name = "Apple";

// Function definition
function MyFunction() {

    // Local variable declaration
    let num = 45;

    // Display the value of Global variable
    console.log(Name);

    // Display the value of local variable
    console.log(num);
}

// Function call
MyFunction();

Output: 

Apple
45

JavaScript Operators

JavaScript operators are symbols that are used to compute the value or in other words, we can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute the value, and Assignment operators ( =, +=, %= ) are used to assign the values to variables.

Example: This example shows the use of javascript operators.

JavaScript
// Variable Declarations
let x, y, sum;

// Assign value to the variables
x = 3;
y = 23;

// Use arithmetic operator to
// add two numbers
sum = x + y;

console.log(sum);

Output
26

JavaScript Expressions

Javascript Expression is the combination of values, operators, and variables. It is used to compute the values.

Example: This example shows a JavaScript expression.

JavaScript
// Variable Declarations
let x, num, sum;

// Assign value to the variables
x = 20;
y = 30

// Expression to divide a number
num = x / 2;

// Expression to add two numbers
sum = x + y;

console.log(num + "\n" + sum);

Output
10
50

JavaScript Keywords

The keywords are the reserved words that have special meanings in JavaScript. 

// let is the keyword used to
// define the variable
let a, b;

// function is the keyword which tells
// the browser to create a function
function GFG(){};

JavaScript Comments

The comments are ignored by the JavaScript compiler. It increases the readability of code. It adds suggestions, Information, and warning of code. Anything written after double slashes // (single-line comment) or between /* and */ (multi-line comment) is treated as a comment and ignored by the JavaScript compiler.

Example: This example shows the use of javascript comments.

JavaScript
// Variable Declarations
let x, num, sum;

// Assign value to the variables
x = 20;
y = 30

/* Expression to add two numbers */
sum = x + y;

console.log(sum);

Output
50

JavaScript Data Types

JavaScript provides different datatypes to hold different values on variables. JavaScript is a dynamic programming language, which means do not need to specify the type of variable. There are two types of data types in JavaScript. 

  • Primitive data type
  • Non-primitive (reference) data type
// It store string data type
let txt = "GeeksforGeeks";

// It store integer data type
let a = 5;
let b = 5;

// It store Boolean data type
(a == b )

// To check Strictly (i.e. Whether the datatypes
// of both variables are same) === is used
(a === b)---> returns true to the console
 
// It store array data type
let places= ["GFG", "Computer", "Hello"];

// It store object data (objects are 
// represented in the below way mainly)
let Student = {
    firstName: "Johnny",
    lastName: "Diaz", 
    age: 35, 
    mark: "blueEYE"
}

JavaScript Functions

JavaScript functions are the blocks of code used to perform some particular operations. JavaScript function is executed when something calls it. It calls many times so the function is reusable.

Syntax: 

function functionName( par1, par2, ....., parn ) {  
    // Function code
}  

The JavaScript function can contain zero or more arguments.

Example: This example shows the use of Javascript functions.

JavaScript
// Function definition
function func() {

    // Declare a variable
    let num = 45;

    // Display the result
    console.log(num);
}

// Function call
func();

Output
45

JavaScript Identifiers

JavaScript Identifiers are names used to name variables and keywords and functions.

A identifier must begin with:

  • A letter(A-Z or a-z)
  • A dollar sign($)
  • A underscore(_)

Note: Numbers are not allowed as a first character in JavaScript Identifiers.

JavaScript Case Sensitive

JavaScript Identifiers are case-sensitive.

Example: Both the variables firstName and firstname are different from each other.

JavaScript
let firstName = "Geek";
let firstname = 100;

console.log(firstName);
console.log(firstname);

Output
Geek
100

JavaScript Camel Case

In JavaScript Camel case is preferred to name a identifier.

Example:

let firstName
let lastName

JavaScript Character Set

A unicode character set is used in JavaScript. A unicode covers the characters, punctuations and symbols.

We have a complete article on character sets. Click here to read Charsets article.

JavaScript Syntax – FAQs

What is the basic syntax of JavaScript?

The basic syntax of JavaScript includes statements, expressions, variables, functions, operators, and control flow constructs. A typical JavaScript statement ends with a semicolon and can include variable declarations, function calls, loops, and conditionals.

What is the syntax for defining a JavaScript function?

The syntax for defining a function in JavaScript is:

function functionName(parameter1, parameter2) {

// Code to be executed

}

This function can then be called using functionName(argument1, argument2);.

Is JavaScript syntax easy to learn?

Yes, JavaScript syntax is considered easy to learn, especially for beginners. It is intuitive and has a C-like structure, which is familiar to those who have experience with languages like C, C++, or Java.

What is the JavaScript syntax for embedding code in HTML?

JavaScript code is embedded in HTML using the <script> tag. The script can be placed within the <head> or <body> sections of the HTML document, or it can be included as an external file:

<script>

// JavaScript code here

</script>

What does “syntax” mean in coding?

In coding, “syntax” refers to the set of rules that defines the structure and format of the code in a programming language. It dictates how code should be written so that it can be correctly interpreted and executed by the compiler or interpreter.



Previous Article
Next Article

Similar Reads

Explain the benefits of spread syntax & how it is different from rest syntax in ES6 ?
Spread Operator: Spread operator or Spread Syntax allow us to expand the arrays and objects into elements in the case of an array and key-value pairs in the case of an object. The spread syntax is represented by three dots (...) in JavaScript. Syntax: var my_var = [...array]; Benefits of using Spread syntax: 1. It allows us to include all elements
4 min read
What is the syntax for leading bang! in JavaScript function ?
Before we get to know the syntax for the leading bang! in a JavaScript function, let's see what functions in JavaScript are actually are. JavaScript functions are a set of statements(procedures) that perform some tasks or calculate some value. A function may take some input and return the result to the user. The main idea to use functions is to avo
2 min read
JavaScript Spread Syntax (...)
The spread syntax is used for expanding an iterable in places where many arguments or elements are expected. It also allows us the privilege to obtain a list of parameters from an array. The spread syntax was introduced in ES6 JavaScript. The spread syntax lists the properties of an object in an object literal and adds the key-value pairs to the ne
4 min read
What is the Syntax for Declaring Functions in JavaScript ?
Generally, in JavaScript, the function keyword is used to declare a variable. But, there are some more ways available in JavaScript that can be used to declare functions as explained below: Using function keyword: This is the most common way to declare functions in JavaScript by using the function keyword before the name of the function.Declaring a
1 min read
How to Create and Use a Syntax Highlighter using JavaScript?
A syntax highlighter is a tool that colorizes the source code of programming languages, making it easier to read by highlighting keywords, operators, comments, and other syntax elements in different colors and fonts. In JavaScript, you can create a syntax highlighter by either manually writing your own code or by using existing libraries. These are
3 min read
ES6 Top features and syntax
ES6 or as it is officially called: ECMAScript2015 is a new JavaScript implementation and is arguably the hottest topic in the JS developer's conventions and meetups why it should not be: JavaScript rules the web and is gaining a foothold in every other field possible, be it robotics(nodebots), desktop applications(using ion framework), chatbots, et
3 min read
XML | Syntax
Prerequisite: XML | Basics In this article, we are going to discuss XML syntax rule which is used while writing an XML document or an XML application. It is a very simple and straight forward to learn and code. Below is a complete XML document to discuss each component in detail. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
3 min read
Shorthand Syntax for Object Property Value in ES6
Objects in JavaScript are the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript primitive data-types (Number, String, Boolean, null, undefined, and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types). The sho
1 min read
SASS Syntax
SASS supports two types of syntax. Each one can be differently used to load your required CSS or even the other syntax. 1. SCSS: The SCSS syntax uses .scss file extension. It is quite similar to CSS. You can even say that SCSS is a superset of CSS, meaning that all the valid CSS is also valid SCSS too. Due to its similarity with CSS, it is the easi
2 min read
How to do HTML syntax highlighting inside PHP strings ?
Syntax highlighting is the work of code editors such as Sublime Text, Visual Studio, Dev CPP, etc, which highlights all the different parts of the source code depending on their syntax by color, modified fonts, or through graphical changes. Since color highlighting these days is integrated into all common editors and development areas. Highlighting
3 min read
How to highlight syntax in files using Node.js ?
Node.js supports modules and packages that can be installed using NPM, which allows us to exploit various functionalities. One such functionality is syntax highlighting using Node.js that helps us to render highlighted code as static HTML, or we can also use it for dynamic syntax highlighting. The following approach covers how to highlight syntax f
2 min read
How to do syntax checking using PHP ?
Syntax checking is one of the most important tasks in programming. Our compiler checks our code and shows relevant errors if there is any in the code i.e. compile time, run time, syntax, etc. We can do the same thing i.e. syntax checking in PHP. In this article, we are going to learn how we can do syntax checking in PHP. The syntax is basically a s
2 min read
Which tag is used to find the version of XML and syntax ?
Extensible Markup Language (XML) is a markup language, defining a ruleset for encoding documents in both formats that is human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. XML is designed to be self-descriptive along with storing and transporting the data. It is a textual
2 min read
How to use class syntax in Typescript ?
Classes: The class keyword was introduced in ES2015. TypeScript fully supports 'class' keyword. classes are a template for creating objects. A Class is a user defined data-type which has data members and member functions. Data members are the data variables and member functions are the functions used to manipulate these variables and together these
2 min read
Less.js Extend Syntax & Inside Ruleset
LESS.js is one of the most popular CSS preprocessor languages because of its many features like mixins, imports, variables, and, so on, which help to reduce the complexity of CSS code. One such important and useful feature of LESS is the @extend directive. In this article, we will see the basic usage of the extend feature in LESS.js, along with kno
2 min read
How to Hide the VueJS Syntax While the Page is Loading ?
Vue.js is a JavaScript framework used in building powerful and elegant user interfaces. In this article, we will learn how to hide the VueJS syntax while the page is loading. This approach ensures that users don't see the uncompiled Vue.js syntax during the initial page load, providing a smoother user experience. The following approaches can be use
3 min read
Provide the syntax for optional parameters in TypeScript
In TypeScript, optional parameters allow you to specify that a function parameter may be omitted when calling the function. You denote optional parameters by adding a question mark (?) after the parameter name in the function declaration. Syntax:function functionName(param1: type, param2?: type, param3?: type) { // Function body } Parameters:param1
2 min read
What is the syntax of creating classes in TypeScript?
Classes in TypeScript are defined as a blueprint for creating objects to utilize the properties and methods defined in the class. Classes are the main building block of the Object Oriented Programming in TypeScript. The classes in TypeScript can be created in the same way as we create them in Vanilla JavaScript using the class keyword. Classes help
1 min read
Bulma Modifiers Syntax
Modifiers in Bulma are used to manipulate a particular class in order to get the desired output. To implement the modifiers, one has to either use the is- or the has- modifier class before the modifier name. It is essential to know the syntax of these modifiers in order to implement them in our code. Syntax: <div class = "is-modifier-name" ...
2 min read
How to Handle Syntax Errors in Node.js ?
If there is a syntax error while working with Node.js it occurs when the code you have written violates the rules of the programming language you are using. In the case of Node.js, a syntax error might occur if you have mistyped a keyword, or if you have forgotten to close a parenthesis or curly brace. Example: Of Syntax Error [GFGTABS] JavaScript
4 min read
Explain the arrow function syntax in TypeScript
Arrow functions in TypeScript are implemented similarly to JavaScript (ES6). The main addition in TypeScript is the inclusion of data types or return types in the function syntax, along with the types for the arguments passed into the function. What is arrow function syntax in TypeScript?Arrow functions in TypeScript offer a concise syntax for defi
3 min read
Syntax to create function overloading in TypeScript
Function overloading is a feature in object-oriented programming where multiple functions can have the same name but different parameters. The parameters can differ in number, types, or both. This allows a single function name to perform different tasks based on the input parameters. Syntax: function function_name(parameter1 : data_type, parameter2
2 min read
How ReactJS ES6 syntax is different compared to ES5 ?
Both ES6 and ES5 are Javascript scripting languages in the development industry. ECMA Script or ES is a trademarked scripting language made by ECMA International. The European Computer Manufacture Association or ECMA is used for client-side scripting for the worldwide web. ES5 was released in 2009 and ES6 in 2015. ES5 was good but lengthy. The new
6 min read
jQuery Syntax
The jQuery syntax is essential for leveraging its full potential in your web projects. It is used to select elements in HTML and perform actions on those elements. jQuery Syntax$(selector).action()Where - $ - It the the shorthand for jQuery function.(selector) - It defines the HTML element that you want to selectaction() - It is the jQuery method u
2 min read
Binding Syntax In Angular
In Angular, binding syntax lets you determine the channel of data transmission between the component class and the template. Among various types of bindings supported by Angular are interpolation, property binding, event binding, and two-way-data-binding. Therefore, it is important to understand various type of binding in order to approximately rel
3 min read
PHP Syntax
PHP, a powerful server-side scripting language used in web development. It’s simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML. Basic PHP SyntaxPHP code is executed b
4 min read
CSS Syntax
CSS syntax refers to the structure of writing CSS code to apply styles to HTML elements. A CSS rule consists of a selector that identifies the element(s) to style, followed by a declaration block containing one or more declarations that specify the styling. Components of a CSS RuleThe general structure of a CSS rule is: selector { property: value;}
3 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important attribute of <script> tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. <script> cons
4 min read
three90RightbarBannerImg