Introduction to JavaScript

Basic Syntax and Variables in JavaScript

high-level programming language

High-level programming language.

In this unit, we will delve into the basic syntax rules of JavaScript and learn about variables.

Basic Syntax Rules in JavaScript

JavaScript syntax refers to the set of rules that define how a JavaScript program should be written and structured. Here are some basic rules:

  • Case Sensitivity: JavaScript is case-sensitive. This means myVariable and myvariable are two different variables.
  • Statements: JavaScript statements are commands that tell the browser what to do. They are often ended with a semicolon (;).
  • Whitespace: JavaScript ignores multiple spaces. You can add white space in your script to make it more readable.
  • Comments: Comments are used to explain the code and they are ignored by the browser. Single-line comments start with // and multi-line comments start with /* and end with */.

Introduction to Variables

Variables are fundamental to all programming languages. They are used to store data values. In JavaScript, we declare variables using the var, let, or const keywords.

  • var: This keyword is used to declare a variable. It can be reassigned and used throughout your whole program.
  • let: This keyword is also used to declare a variable, but the variable can only be used in the block of code in which it is defined.
  • const: This keyword is used to declare a variable that cannot be reassigned. It is a constant, as the name suggests.

Here is an example of how to declare and assign variables:

var name = 'John'; let age = 30; const pi = 3.14;

In the above example, name is a variable declared with var and assigned the string 'John'. age is a variable declared with let and assigned the number 30. pi is a constant declared with const and assigned the value 3.14.

Naming Conventions for Variables

When naming your variables, it's important to follow certain conventions:

  • Variable names should be descriptive and reflect the data they hold.
  • They cannot start with a number.
  • They can contain letters, numbers, underscores, and dollar signs.
  • They cannot contain spaces or special characters.
  • JavaScript uses camel case for multi-word variable names (e.g., myVariableName).

Understanding the basic syntax and variables is crucial in learning JavaScript as it forms the foundation for more complex concepts. In the next unit, we will explore data types and how they are used in JavaScript.