JavaScript Basics
This article explains the basics of JavaScript.
YouTube Video
Executing Hello World!
JavaScript Overview
JavaScript is one of the most widely used programming languages in web development. It is primarily used to add dynamic elements to web pages, allowing for user interface manipulation, data transmission, and animation creation. It can operate on the client-side (in a browser) and server-side using technologies like Node.js. Due to its simplicity and flexibility, it is easy for beginners to learn and is widely used by professional developers.
Variables in JavaScript
Variables in JavaScript are like containers used to store and reuse data. By using variables, you can maintain and manipulate values in your program.
Variable Declaration
In JavaScript, there are three keywords for declaring variables.
var
: An old method of declaring variables, but handling its scope is complex and requires caution. It is based on function scope.
1var x = 10;
let
: Introduced in ES6, it is a way to declare variables with block scope. It can be reassigned but cannot be redeclared in the same scope.
1let y = 20;
const
: Used to declare variables that are immutable (constants). It has block scope and cannot be reassigned or redeclared after declaration.
1const z = 30;
Scope
Variables have the concept of scope.
Global Scope
1var globalVar = 'This is global'; // Global scope
2
3function accessGlobal() {
4 console.log(globalVar); // Able to access global variable
5}
6
7accessGlobal(); // Outputs "This is global"
- Global scope variables are accessible from anywhere. Variables declared with
var
have global or function scope, butlet
andconst
have block scope.
Block Scope
1if (true) {
2 let localVar = "This is a block-scoped variable";
3
4 // Accessible inside the brackets
5 console.log(localVar);
6}
7
8// Error: localVar cannot be used outside of this scope
9console.log(localVar);
-
Block scope: Variables declared with
let
orconst
are valid only within{}
(curly braces). -
An error occurs when accessing from outside
{}
(curly brackets).
Function Scope
1function myFunction() {
2 var functionScoped = 'This is function scope';
3 // Accessible inside the function
4 console.log(functionScoped);
5
6 if (true) {
7 var functionVar = 'This is also function scope';
8 }
9 // functionVar can be used inside of the fucntion
10 console.log(functionVar);
11}
12
13myFunction(); // Outputs "This is function scope"
14
15// Error: functionScoped is not defined
16console.log(functionScoped);
-
Function scope: Variables and functions defined inside a function cannot be accessed from outside the function. Variables declared inside a function with
var
belong to this scope. -
In this example, the variable
functionVar
can be accessed from outside the{}
(curly braces) as long as it is within the function scope. On the other hand, accessing the variablefunctionScoped
from outside the function scope results in an error.
Thus, variables declared with var have only function scope and no block scope, posing a risk of being used in unexpected ranges. It is preferable to use const for variables that do not change and usually use let, avoiding the use of var as much as possible.
Data Types
JavaScript variables can store values of various data types. There are string
for handling text and number
for handling numeric values.
The main data types are as follows:.
1// Number: Numeric type (integer and floating point number)
2let integerNumber = 42;
3let floatNumber = 3.14;
4console.log("Number (Integer):", integerNumber);
5console.log("Number (Float):", floatNumber);
6
7// String: String type
8let text = "Hello, JavaScript!";
9console.log("String:", text);
10
11// Boolean: Boolean type (true or false)
12let isJavaScriptFun = true;
13let isError = false;
14console.log("Boolean (true):", isJavaScriptFun);
15console.log("Boolean (false):", isError);
16
17// Null: Explicitly represents "nothing"
18let emptyValue = null;
19console.log("Null:", emptyValue);
20
21// Undefined: The default value assigned to an uninitialized variable
22let notDefined;
23console.log("Undefined:", notDefined);
24
25// Symbol: A data type for creating unique values
26let uniqueKey = Symbol("id");
27console.log("Symbol:", uniqueKey);
- Primitive Types:
number
: Handles numerical values (integers and floating-point numbers).string
: Handles strings of characters.boolean
: Handles boolean valuestrue
orfalse
.null
: Explicitly represents a value of 'nothing'.undefined
: A value automatically assigned to variables that have not been initialized.Symbol
: A data type used to create unique values.
1// Object: A data structure that holds multiple properties
2let person = {
3 name: "Alice",
4 age: 25,
5 isStudent: false
6};
7console.log("Object:", person);
8console.log("Object Property (name):", person.name);
9console.log("Object Property (age):", person.age);
10
11// Array: A list that holds multiple values
12let numbers = [10, 20, 30, 40];
13console.log("Array:", numbers);
14console.log("Array Element (index 0):", numbers[0]);
15
16// Function: A function object
17function greet(name) {
18 return "Hello, " + name + "!";
19}
20console.log("Function Output:", greet("Bob"));
21
22// Another way to define a function using arrow syntax
23let add = (a, b) => a + b;
24console.log("Arrow Function Output (3 + 5):", add(3, 5));
- Object Types:
Object
: A data structure with multiple properties.Array
: A list containing multiple values.Function
: A function object.
Assignment and Reassignment to Variables
Variables declared with let
or var
can be reassigned, but const
cannot be reassigned once declared.
1let score = 100;
2score = 150; // Correct
3
4const pi = 3.14;
5pi = 3.14159; // Error
Variable Hoisting
In JavaScript, there is a phenomenon where variable declarations are 'hoisted' to the top of their scope. Variables declared with var
are hoisted, but using let
or const
before declaration causes an error.
1console.log(a); // undefined
2var a = 10;
3console.log(a); // 10
- In this case, variables declared with
var
are hoisted, and their values are output.
1console.log(b); // ReferenceError
2let b = 20;
- Variables declared with
let
are not hoisted, resulting in an error.
Proper Use of Variables
Consider the following points for proper use of variables.
- Prefer using
const
and avoid usingvar
. - Follow variable naming conventions.
- Use
camelCase
, such asuserName
ortotalPrice
. - Avoid ambiguous names like
data
orvalue
, and use meaningful names to improve readability. - A variable name cannot start with a number, so names like
1variable
are not allowed.
- Use
- Excessive use of global variables can cause scope ambiguity and lead to bugs, so avoid using them whenever possible.
Summary
var
: An old variable declaration method that has function scope.let
: A block-scoped variable that can be reassigned.const
: A block-scoped variable that cannot be reassigned (constant).- It is important to use variables according to their data types and be mindful of their scope.
What are escape characters in JavaScript?
Escape characters are a method used to represent characters with special meanings within regular string literals. In JavaScript, escape characters are introduced with a backslash \
to impart special effects to a string or to include control characters. Escape characters are useful for including elements like newlines, tabs, or quotation marks in a string.
Examples of using escape characters
Below are some sample codes utilizing escape characters.
Escaping double and single quotes
Use escape characters to represent double or single quotes within a string.
1const singleQuote = 'It\'s a beautiful day!';
2console.log(singleQuote); // Output: It's a beautiful day!
3
4const doubleQuote = "He said, \"Hello there!\"";
5console.log(doubleQuote); // Output: He said, "Hello there!"
Escaping backslashes
To include a backslash itself in a string, escape it with \
.
1const path = "C:\\Program Files\\MyApp";
2console.log(path); // Output: C:\Program Files\MyApp
Escaping newlines and tabs
You can insert newlines and tabs to make long strings more readable.
1const multiline = "First line\nSecond line\nThird line";
2console.log(multiline);
3// Output:
4// First line
5// Second line
6// Third line
7
8const tabbed = "Column1\tColumn2\tColumn3";
9console.log(tabbed); // Output: Column1 Column2 Column3
Escaping Unicode characters
Using Unicode escape sequences allows you to represent specific characters with hexadecimal codes.
1const smiley = "\u263A"; // Copyright Mark
2console.log(smiley);
Notes
Excessive use of escapes can harm readability
Overusing escape characters can reduce the readability of your code. It is especially important to use escape characters judiciously in long strings.
Consider using template literals
In JavaScript, template literals using backticks allow you to include newlines or embedded expressions without escape characters.
1const message = `This is a message
2that spans multiple lines`;
3console.log(message);
4// Output:
5// This is a message
6// that spans multiple lines
Summary
Escape characters are essential for representing special or control characters within strings. By escaping single or double quotes and adding newlines or tabs, you can create more flexible strings. However, excessive use of escape characters can make the code harder to read, so consider using template literals when appropriate.
JavaScript Versions
JavaScript has a standard specification called ECMAScript (ES). JavaScript has evolved based on this standard. Below is a brief description of its major versions.
-
ES3 (1999)
The first widely adopted version. Basic syntax and features were established.
-
ES5 (2009)
Introduction of
strict mode
, and new features likeArray.prototype.forEach
,Object.keys
, etc. were added. -
ES6 / ES2015 (2015)
A major update to JavaScript has been made. Many features foundational to modern JavaScript, such as
let
,const
,arrow functions
,classes
,promises
,modules
, etc., were introduced. -
ES7 / ES2016 (2016)
Array.prototype.includes
and theExponentiation Operator (**)
were added. -
ES8 / ES2017 (2017)
async/await
was introduced, making it simpler to write asynchronous processes. -
ES9 / ES2018 (2018)
Asynchronous iterators and
Rest/Spread Properties
were added. -
ES10 / ES2019 (2019)
flatMap
andObject.fromEntries
were added. -
ES11 / ES2020 (2020)
Optional Chaining (?.)
and theNullish Coalescing Operator (??)
were added, allowing code to be written more simply and safely. -
ES12 / ES2021 (2021)
String.prototype.replaceAll
andPromise.any
, among others, were added. -
ES13 / ES2022 (2022)
Array.prototype.at
and classprivate
fields (#field
), among others, were added. -
ES14 / ES2023 (2023)
Array.prototype.toSorted
andSymbol.prototype.description
, among others, were added. -
ES15 / ES2024 (2024)
Promise.withResolvers
for easierPromise
management and resizableArrayBuffer
, among others, were added.
Current JavaScript is updated every year, and new features are added even in the latest version.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.