Learning JavaScript is so much important today because of the huge number of opportunities that you get. JavaScript is not limited to web development but also desktop, mobile, and other exciting areas.
There are many things to learn in JavaScript and it can be confusing. In this guide, you will get an overview of quick essentials that will help you to take a step ahead in learning JavaScript. However, you should have a basic understanding of programming before reading this article.
Programming in JavaScript – JavaScript Essentials
Data Types
Primitive Types
They are the simple data types that are stored and copied around as values. They are:
- Number – Any positive or negative integer, fractions, etc. such as 13, -10, 22.5
- String – Characters inside quotes (double or single) such as ‘hello’, “I am good”.
- Boolean – Values “true” and “false” without quotes.
You can use the “typeof” operator to find the type of the variable.
Reference Types
Types that are complex and made up of other primitive types are called reference types. They store the reference to the data in the variables and not the value itself. They cannot be copied just by assigning them to some other variable, it just will create an alias for that variable. Instead, we have to clone them using various techniques like slicing and spreading. They are:
- Arrays – List of values. Eg: [2, ‘sun’, ‘moon’, true, 51]
- Objects – Key-value pairs. Eg: { name: ‘John’, title: ‘Hello world’ }
const num = 12 const str = 'hello' var bool = true const array = [5, 3, 12] let obj = { title: 'HTML' } console.log(typeof num, typeof str, typeof bool) // number string boolean console.log(typeof array, typeof obj) // object object // array is internally an object in javascript
Operators
All operators that you have learned in any standard programming language are included in JavaScript. They include
- Arithmetic (+, -, *, /, %) and (+=, -=, *=, /=, %=)
- Relational (<, >, ==, !=, <=, >=)
- Logical (&&, ||, !)
But JavaScript has two extra ones in relational operators: Strict Equality or identity (===) and Strict Inequality (!==). The only difference between (== and ===) is that equality will convert the values to similar types before comparing while strict will not.
console.log('5' == 5) // true, as '5', 5 are converted to similar types first console.log('5' === 5) // false, it does not do type conversion
Common Constructs in JavaScript – JavaScript Essentials
Variables
We can declare variables in javascript using the keywords “let”, “const”, and “var”. All three of them have different purposes.
- Use let when you need to create a lexically scoped variable.
- “var” is scoped anywhere inside the function where it is defined.
- “cosnt” is lexically scoped and its value cannot be changed once declared.
Arrays
Arrays are declared inside square brackets ([]) and they have useful methods like .length() and .sort(). They can have a mix of any types and even have “arrays of objects” or “arrays of arrays” and other nested combinations.
let someVariable = 'hello' const nestedArray = [12, someVariable, 'test', [1, 2], 'html']
Objects
Objects in javascript are just a collection of key and value pairs that can be accessed using the dot notation or square bracket notation like associative arrays. JS Objects are not the same as classes and objects in Object-Oriented Programming. It can have properties or methods (functions).
let user = { name: 'John', age: 30, } console.log(user.name, user.age) // John 30
Functions
We can use the “function” keyword or arrow functions to declare them. Calling a function is the same as in other languages.
However, JavaScript has two extra concepts:
1. Anonymous functions: Functions that don’t have a function name.
2. Functions expressions: A javascript functions can be stored and passed around like variables. When we define a function anonymously and use them to form an expression, like storing them in a variable, it becomes a function expression.
function add(num1, num2) { const res = num1 + num2 return res } console.log(add(3, 2)) // 5
Conditionals
The if statement and the conditional operator (?:) are available for us to perform checks. There is short circuit evaluation in JavaScript, so if the first operator is true in OR operation, there is no need to evaluate the second one, similar for AND operation. In addition to that, the value of the OR or AND operation is returned and can be stored in a variable.
const isWorking = false const value = isWorking || 'not working' console.log(value) // “not working”
Loops
There are all the standard loops like for, while, and do-while, along with some extra ones like .forEach(), .map(), “for of”, and “for in” loop.
const array = ['apple', 'grapes', 'peanuts'] for (let item of array) { console.log(item) } /* apple grapes peanuts */
Running JavaScript
To run the JavaSript Code, we can use the node runtime environment. NodeJS allows the execution of javascript code outside of the browser. Once you install NodeJS we can simply use the command “node yourprogram.js” to execute the code in the terminal.
Web Development in JavaScript (client-side)
The original use of javascript was to develop interactive websites for users. JavaScript is the only language that a browser understands. It is in increasing demand today with the advent of client-side frameworks like React, Angular, and Vue.
Using them, we can now create single-page web apps that offer an app-like experience without reloading a single page. Their core is nothing but client-side javascript.
DOM (Document Object Model)
In the browser, every HTML element is represented in an equivalent tree structure with its properties and methods. This is the Document Object Model. Using this model, JavaScript can manipulate the HTML elements and its CSS styling easily.
Selecting DOM elements
When we provide id or classname to an html element, we can select them by javascript using these common selectors.
- document.getElementById(‘id’)
- document.getElementsByClassName(‘classname’)
- document.querySelector(‘cssselector’)
- document.querySelectorAll(‘cssselector’)
Once we select the element, you can now use properties like:
- innerHTML – To set the html content of the element
- innerText – To set the text content of the element
- style.propertyName – Update the style of the elment such as element.style.color = ‘red’
- getAttribute(‘attributeName’) – You can get the attribute value of the element.
- setAttribute(‘name’, ‘value’) – You can set an attribute value for the element.
Events in JavaScript
Most of the time all the JavaScript is not executed directly on the load of an HTML page. Most of the code runs when the user starts interacting with the web page, by firing events.
JavaScript can handle mouse clicks, form submissions, and run code when one of these happens. Events can be a click, double click, keyboard press, or change of a form value.
We can run code whenever an event is triggered or fired using the addEventListener() method in JavaScript.
Here are some of the common events in javascript:
- load
- click
- mouseover
- submit
- input
- change
- keydown
addEventListener(‘eventName’, event handler)
The event name can be any valid event name in javascript like click, load. The event handler is a function that is called every time the event is fired. Events and DOM handling comprise around 80% of the JavaScript code in Client Side Programming. So, knowing them will allow you to manipulate and build interactive web pages.
Combining events and DOM manipulation helps us to create interactive features as shown by this simple example.
HTML Code
<body> <button id="btn"> Change Text </button> <p id="text">Default Text</p> </body> <script src="script.js"></script>
JavaScript Code
const btn = document.getElementById('btn') const p = document.getElementById('text') btn.addEventListener('click', function () { // appends (Updated) to the text content p.innerText = '(Updated) ' + p.innerText })
Browser Output
Now every time we click the button, it appends the “(Updated)” string to the text.
Conclusion
Knowing and learning JavaScript well can take you ahead in your career. It opens the doorway to many other paths like becoming a frontend or backend developer, mobile developer, and desktop developer. Here you will find more articles on JavaScript.