JavaScript is the de facto language to create web apps as it is the only language supported by browsers. Over time, JavaScript has evolved from only a programming language for the web to a Cross-Platform Object-Oriented Programming Language, that is, a programming language supported by multiple Operating Systems and it follows the Object-Oriented Programming paradigm, where everything is an object.
How to run JavaScript code?
If you want to use JavaScript only for Web Development, any modern browser would suffice for this purpose. All modern browsers support JavaScript and you will be able to execute the scripts linked in your HTML code like:
<script src="./script.js"></script>
If you want to unlock the full capabilities of JavaScript and use it as a programming language, you will have to install Node.js. After installing node use the following command to check if it has been installed correctly.
$ node -v
v14.15.0
Your version might be different, but as long as you don’t get an error, you are good to go.
Basics of JavaScript
Let’s go through the basics of JavaScript. Since JavaScript is a weakly typed language, the data types are not important as you can use the same variable to store different data types in different parts of the script.
Data Types
Even though JavaScript doesn't have strict data type binding, you should be aware of the data types available in JavaScript.
String
Strings is the data type used to store text values. To define a string, use single or double-quotes.
let stringVariable = "Some String";
You can also use backtick for multi-line string or string template, where the data is passed on to the string between dollar symbol and curly braces.
let multiLineStringVariable = `
This is a
Multi-line string.
`;
let stringTemplateVariable = `String Templating: ${multiLineStringVariable}`;
Number
Unlike most programming languages, JavaScript does not support different data types for integer
and float
. Numbers can be used to store both whole numbers and fractional numbers.
const wholeNumber = 1;
const fractionalNumber = -1.4;
Boolean
Booleans can be used to store truth values, that is, true or false.
let flag = true;
flag = false;
Undefined
Undefined is used to define a value that has not been defined yet.
let variable;
In this case, since the variable has not been initialized, its value is undefined.
Null
Null is used to define where the is no value at all.
const variable = null;
Conditionals
You can execute parts of the code only when a certain condition is met.
let shouldLog = true;
if (shouldLog) {
console.log("Logging changes");
}
In this example, we log only when shouldLog
is true.
You can also use comparison operators and logical operators for complex conditions.
Comparison Operators
Let's consider x = 5
Operator | Description | Comparing | Returns |
---|---|---|---|
=== | equal value and equal type | x === 5 | true |
!== | not equal value or not equal type | x !== 5 | false |
> | greater than | x > 8 | false |
< | less than | x < 8 | true |
>= | greater than or equal to | x >= 8 | false |
<= | less than or equal to | x <= 8 | true |
==
and !=
operators are also supported, but using them is not suggested as they lead to unexpected results like:
> 0 == '0'
true
> 0 == []
true
> '0' == []
false
Logical Operators
Let's consider x = 5
and y = 3
Operator | Description | Example | Returns |
---|---|---|---|
&& | and | (x < 10 && y > 1) | true |
\ | \ | or | |
! | not | !(x == y) | true |
Arrays
If you want to store a collection of items in a variable, you can use Arrays.
const numberArray = [1, 2, 3, 4, 5];
// adding an element to the `numberArray`
numberArray.push(6);
// removing the last element from the `numberArray`
numberArray.pop();
Loops
JavaScript supports for
and while
loops.
For Loop
For loops are the go-to choice when you know the number of iterations for the loop.
const numberArray = [1, 2, 3, 4, 5];
for (let index = 0; index < numberArray.length; index++) {
const element = numberArray[index];
console.log(element);
}
While Loop
While loops are effective when you don’t know how many iterations the loop will run for. It takes a condition and keeps on running till the condition is true.
const numberArray = [1, 2, 3, 4, 5];
let itemCount = 0;
while (numberArray.pop() !== undefined) {
itemCount += 1;
}
var
vs let
vs const
JavaScript allows you to define data items using var
, let
and const
, when to use which? var
creates a global variable, let
creates a variable with local scope, that is, it will live only inside the block it is defined in and const
is used to create a constant.
var globalVariable = "I can be accessed throughout the script";
const constant = "I CANNOT be changed";
if (true) {
let localVariable = "I can only be used inside this if block";
}
Using JavaScript in the browser
Using JavaScript in the browser gives you access to the DOM, or the Document Object Model, which enables you to manipulate the HTML using JavaScript.
Let’s say you have an input on your page:
<input type="text" id="test-input" />
You can get access to the input in your JavaScript script and modify it to your desire or add event listeners to
const inputElement = document.getElementById("test-input");
// styling the element
inputElement.style.borderRadius = "6px";
// adding event listener on element click
inputElement.addEventListener("click", function (event) {
console.log("Input Element Clicked");
});
Using JavaScript with Node.js
If you use JavaScript with Node.js, you cannot access the DOM as it is created by the browser, but you will be able to access the file system, something you cannot do while using JavaScript from the browser.
const fs = require("fs");
const path = require("path");
const filePath = path.join(__dirname, "temp.txt");
const rawData = fs.readFileSync(filePath);
const data = rawData.toString();
console.log(data.toString());
To run the script use:
node <filename>.js
Conclusion
In this article, we learned the basics of JavaScript, what it is and how to get started with using it. We also learned how to use it in the browser and locally as per our requirements. Now it’s your turn to use it in your project and turn your ideas into reality.
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript
Top comments (0)