Basic Syntax and Operations in JavaScript
Understanding the basic syntax and operations of JavaScript is crucial for writing efficient and effective code. This guide will introduce you to the foundational elements of JavaScript, including variables, data types, operators, and basic syntax rules.
Variables
Variables are used to store data that can be referenced and manipulated in your program. In JavaScript, you can declare variables using var
, let
, or const
.
var
: Declares a variable, optionally initializing it to a value. It has function scope.let
: Declares a block-scoped local variable, optionally initializing it to a value.const
: Declares a block-scoped constant, which must be initialized at the time of declaration and cannot be reassigned.
var name = 'John';
let age = 25;
const isStudent = true;
Data Types
JavaScript supports various data types, which can be broadly categorized into primitive types and objects.
- Primitive Types:
String
: Represents textual data. Example:'Hello, World!'
Number
: Represents numeric values. Example:42
Boolean
: Represents logical values, eithertrue
orfalse
. Example:true
Undefined
: Represents a variable that has been declared but not assigned a value.Null
: Represents the intentional absence of any object value.Symbol
: Represents a unique and immutable value, often used as object keys.
- Objects:
- Complex data structures that can store collections of data and more complex entities.
Operators
Operators are symbols that perform operations on variables and values. Here are some of the most commonly used operators:
- Arithmetic Operators:
+
,-
,*
,/
,%
(modulus),++
(increment),--
(decrement)let a = 10; let b = 5; console.log(a + b); // 15 console.log(a - b); // 5
- Assignment Operators:
=
,+=
,-=
,*=
,/=
,%=
let x = 10; x += 5; // x is now 15
- Comparison Operators:
==
,===
(strict equality),!=
,!==
(strict inequality),>
,<
,>=
,<=
let c = 10; console.log(c == '10'); // true console.log(c === '10'); // false
- Logical Operators:
&&
(and),||
(or),!
(not)let isTrue = true; let isFalse = false; console.log(isTrue && isFalse); // false console.log(isTrue || isFalse); // true
Basic Syntax Rules
- Case Sensitivity: JavaScript is case-sensitive. This means
myVariable
andmyvariable
would be considered different variables. - Statements and Semicolons: Each statement in JavaScript should end with a semicolon (
;
). However, JavaScript can automatically insert semicolons (ASI
) in certain situations, but relying on this feature is not recommended. - Comments: Comments can be added using
//
for single-line comments and/* */
for multi-line comments.// This is a single-line comment /* This is a multi-line comment */
Example Code
Here’s a simple example that combines variables, data types, and operators:
let name = 'Alice';
let age = 30;
const isEmployed = true;
if (isEmployed) {
console.log(name + ' is employed and is ' + age + ' years old.');
} else {
console.log(name + ' is not employed.');
}
0 Comments