Basic JavaScript for beginners
In this article, we will learn basic javascript — javascript for beginners.
We will learn javascript with basic examples along with challenges. For best practice and learning so let’s start learning and implement these examples and challenges.
JavaScript Variables:
Variables are containers for storing data (storing any type of data and values).
There are 4 Ways to Declare a JavaScript Variable:
Using
var
Using
let
Using
const
Using nothing
Var
Use the reserved keyword var
to declare a variable in JavaScript. A variable must have a unique name. The following declares a variable.
For Example:
x
, y
, and z
, are variables, declared with the var
keyword:
var x = 5;
var y = 6;
var z = x + y;
console.log(z); // answer is 11
Variable Declaration:
var message; // declaring a variable without assigning a value
In the above, the var message;
is a variable declaration. It does not have any value. The default value of variables that do not have any value is undefined
.
You can assign a value to a variable using the =
sign operator when you declare it or after the declaration and before accessing it.
Variable Initialization:
var message;
message = "Hello JavaScript Developer!"; // assigned a string value
console.log(message) // access a variable
//the following declares and assign a numeric value
var num = 100; // assigned a number value
var numValue = num; // assigned a variable to variable
console.log(numValue)
Variable Scope
In JavaScript, a variable has two scopes mean you can declare or initialize the variable with two methods global scope and local scope.
Global Variables
Global variables that can be declared out of any function or block are called global variables. They can be accessed anywhere in the JavaScript code, even inside any function, condition, or loop.
Local Variables
Local variables that can be declared inside the function or block are called local variables to that function. They can only be accessed inside the function where they are declared but you can never access them outside of a function.
Example: Global and Local Variable
var a = "Hello " // global variable
function myfun(){
var b = "JavaScript Developer!";
console.log(a + b); //can access global and local variable
}
myfun();
console.log(a);//can access global variable
console.log(b); //error: can't be access local variable
Variables Declare without var keyword:
Variables can be declared and initialized without the var
keyword. However, a value must be assigned to a variable declared without the var
keyword.
The variables declared without the var
keyword become global variables, irrespective of where they are declared.
For Example:
function myfun(){
message = "Hello JavaScript!";
}
myfun();
console.log(message); // message becomes global variable so can be accessed here
It is Not Recommended to declare a variable without
var
keyword because it can accidentally overwrite an any existing global variable.
Variable Names in JavaScript
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Variable names are case-sensitive in JavaScript. So, the variable names
student
,STUDENT
,Student
,sTudent
are considered separate variables.Variable names can contain letters, digits, or the symbols $ and _.
Variable names always begin with a letter.
A variable name cannot start with a digit 0–9.
A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return cannot be variable names.
Let
Mostly things are the same which is defined in var
above
The let
the keyword was introduced in ES6 (2015).
Variables defined let
cannot be Redeclared.
Variables defined let
must be Declared before use.
Variables defined with let
have Block Scope.
Let cannot be Redeclared
A variable that is defined with let
cannot be redeclared.
You cannot accidentally redeclare a variable.
With let
you can not do this:
For Example:
let x = "Hello JavaScript";
let x = 0;
// SyntaxError: 'x' has already been declared
With var
you can do this
var x = "Hello JavaScript";
var x = 0;
Let is block scoped
Before ES6, JavaScript had only two scopes Global Scope and Function Scope. ES6 introduced two important new JavaScript keywords: let
and const
. These two keywords provide Block Scope in JavaScript. Block scope is always defined in {}
. These brackets called is function brackets
Variables declared inside a { } block cannot be accessed from outside the block:
let calling = "say Hi";
let times = 4;
if (times > 3) {
let hello = "say Hello instead";
console.log(hello);// "say Hello instead"
}
console.log(hello) // hello is not defined
Variables declared with the var
keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
{
var x = 200;
}
// x CAN be used here
let can be re-initialized but not re-declared.
Just like var
, a variable declared let
can be updated within its scope. Unlike var
, a let
variable cannot be re-declared within its scope. So while this will work:
let message = 'Hello JavaScript';
message = 'JavaScript Developer';
Const
Variables are declared with the const
maintain constant values. const
declarations share some similarities with let
declarations.
The const
the keyword was introduced in ES6 (2015).
Variables defined const
cannot be Redeclared.
Variables defined const
cannot be Reassigned.
Variables defined with const
have Block Scope.
Const variables Cannot be Reassigned
A const
the variable cannot be reassigned:
For Example:
const num = 35;
num = 314; // This will give an error
num = num + 10; // This will also give an error
Every const
declaration, therefore, must be initialized at the time of declaration.
JavaScript const
variables must be assigned a value when they are declared:
Correct method:
const num = 100;
Incorrect method:
const num = 100;
num = 200;
When to use JavaScript const?
As a general rule, always declare a variable with const
unless you know that the value will change.
Use const
when you declare:
A new Array
A new Object
A new Function
A new RegExp
JavaScript String:
The JavaScript string is an object that represents a sequence of characters. There are 2 ways to create strings in JavaScript. By string literal. By string object (using the new keyword).
Example:
const string1 = “this is a literal string”;
const string2 = new String(“A string Object”);
let name = "Fahad Ahmad";
console.log(name);
String is a primitive data type in JavaScript. A string is a textual content. It must be enclosed in single or double quotes.
For Example:
"Hello World" // both example are literal string
'Hello World'
The string value can be assigned with a variable using the equal to (=) operator.
For Example:
let str1 = 'Hello JavaScript Developers!';
This is the wrong way to declare and initialize the variable.
let first name = "Fahad"
This is the right way to declare and initialize the variable.
let firstName = "Fahad";
let lastName = "Ahmad";
String Concatenation:
In JavaScript we concatenate the two string with plus (+) operator.
How to concatenate the two strings.
let fullName = 'Fahad' + 'Ahmad';
console.log(fullName);
Same as it how to concatenate two variables by using plus operator.
How to add string between strings.
let fullName = firstName + " " + lastName;
console.log(fullName);
String object:
In the above explanation, we define a string literal to a variable. JavaScript allows you to create a String object using the new
keyword, as shown below example.
var str1 = new String();
str1 = 'Hello World';
// or
var str2 = new String('Hello World');
In the above example, JavaScript returns a String object instead of a primitive String type. It is recommended to use a primitive string instead of a String object.
Be careful when you working with String objects because the comparison of string objects using the == operator compares String objects and not the values. Explain the following example below.
var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;
str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true
typeof(str1); // object
typeof(str3); //string
JavaScript String Methods & Properties
JavaScript string (primitive or String object) Primitive values cannot have properties or methods (because they are not objects) like as “Hello World”
But with JavaScript, methods, and properties also allow for primitive values, because JavaScript treats primitive values as objects when we execute methods and properties.
String Properties:
Length → The length
property returns the length of the string.
For example:
let str = "abcdefghijklmnopqrstuvwxyz";
let length = str.length;
console.log(length) // answer is calculated the total length of given string.
String Methods:
Extracting String Parts in JavaScript:
There are 3 methods for extracting a part of a string:
slice(
start
,
end
)
substring(
start
,
end
)
substr(
start
,
length
)
JavaScript String slice()
Extracts a section of a string based on specified starting and ending index and returns a new string. slice()
extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
Example:
Slice out a portion of a string from position 4 to position 8 (8 not included):
let str = "Apple, Banana, Mango";
let part = str.slice(4, 8);
console.log(part);
Note
JavaScript mostly counts positions from zero.
First position is 0.
Second position is 1.
If a parameter is a negative value, the position is reversed and counted from the end of the string.
For example, slices out a portion of a string from position -10
to position -5
:
Example:
var str = "Apple, Mango, Grapes";
var part = str.slice(-10, -5);
console.log(part);
JavaScript substring():
In Javascript substring()
is similar to slice()
.
The difference between start and end values less than 0 are treated as 0 in substring()
. Returns the characters in a string between start and end indexes.
substring(start, end)
let str = "Honda, Toyota, Suzuki";
let part = str.substring(5, 10);
console.log(part);
If you omit the second parameter, then substring()
will slice out the rest of the string.
JavaScript substr():
In Javascript substr()
is similar to slice()
.
The difference between the second parameter specifies the length of the extracted part. Returns the characters in a string from a specified starting position through the specified number of characters (length).
For Example:
let str = "Toyota, Honda, Suzuki";
let part = str.substr(9, 8);
console.log(part);
If you omit the second parameter, then substr()
will slice out the rest of the string.
For Example:
let str = "Honda, BMW, Audi";
let part = str.substr(5);
console.log(part);
Replace method in JavaScript:
The replace()
the method replaces a specified text or value with another text in a string and returns a new string. This method are also used in search value.
For Example:
let str = "This is a old text";
let newStr = str.replace("This is new text", "by using replace method");
console.log(newStr);
Note
The
replace()
method does not change the string it is called on.
The
replace()
method returns a new string.
The
replace()
method replaces only the first match.
JavaScript String toUpperCase():
Converts a string toUpperCase according to the defining string.
A string is converted to upper case with toUpperCase()
:
For Example:
let str1 = "Convert string to upper case";
let str2 = str1.toUpperCase();
console.log(str2);
JavaScript String toLowerCase():
Converts a string to lower case according to the defining string.
A string is converted to lower case with toLowerCase()
:
For Example:
let str1 = "Convert string to lower case";
let str2 = str1.toLowerCase();
console.log(str2);
JavaScript String trim():
The trim()
method removes whitespace from both sides of a string as trim()
remove space from the start of the string and same as it trim()
remove space from the end of the string.
For Example:
let str1 = " Remove extra spaces ";
let str2 = str1.trim();
console.log(str2);
Challenge 1#
Create two variables for example city, country, and print output.
Output:
JavaScript Numbers:
JavaScript has only one type of number. Numbers can be written with or without decimals.
const num = 5.5;
console.log(num);
Output:
const x = 11;
const num = x + 1 * 2;
console.log(num);
Output: 13
example:
const x = 11;
const num = (x + 1) * 2;
console.log(num);
Output: 24
Challenge 2#
studentScore = 18;
maxScore = 20;
Output student percent = 90;
let studentScore = 18;
let maxScore = 20;
let percent = (studentScore / maxScore) * 100;
console.log(percent);
Challenge #3
Convert temperature Fahrenheit to Celsius.
Formula: (32°F − 32) × 5/9 = 0°C
let fahrenheit = 32;
let celsius = (fahrenheit - 32) * 5 / 9;
console.log(celsius);
Boolean Data Type:
=== — equality operator
!== — not equal operator
< — less than the operator
> — greater than the operator
let temp = 100;
let isFreezing = temp === 100;
console.log(isFreezing);
Output: true
Thanks for reading I hope you like this article and understand some basic JavaScript knowledge. If you want to learn JavaScript please practice it properly and implement with examples. We will discuss next part of basic javaScript in next article.
Follow me and share with friends and waiting for next article. Thanks
Have a nice Day 😊