This article is intended to help you understand the basic building blocks of JavaScript. After working through this article, you should be able to:
list the primitive data types used in JavaScript
create and use variables to store values
add variables to strings with concatenation or interpolation
understand and use operators and conditionals
declare functions with and without parameters
call functions with and without arguments
write ES5 and ES6 functions
This article contains a lot of content, so I highly recommend you work through it in parts. Take a short break every 20 minutes to look away from your screen and move your body for the best learning retention. I recommend this as a best practice for all learning.
What is JavaScript?
JavaScript is a scripting language created to make the web more dynamic. Javascript can be client-side and server-side, meaning it can control user interfaces like in a web browser and server-side extensions that connect with databases. Due to its flexibility and versatility, JavaScript has become the most popular programming language. You will learn there are many different ways to accomplish the same goal in JavaScript.
The easiest way to get started with JavaScript is by using the Developer Tools Console to run code in your web browser. You can open the console in Google Chrome by pressing the hotkeys shortcut command+option+i
, by clicking View -> Developer -> JavaScript Console
, or by right-clicking and selecting Inspect
, then go to Console
tab. Open your console to code along and check out this overview for more information.
Primitive Data Types in JavaScript
Most programming languages have the same basic data types built-in. A data type is defined by the values it can hold and the operations that can be done on it. Primitive data types are also known as simple data types. Primitives in JavaScript are boolean, undefined, null, number, string, and symbol. Use the acronym BUNNSS to remember them.
Boolean: represents one of two values - true or false
Undefined: indicates that a variable has not been assigned a value
Null: represents the intentional absence of a value, nothing!
Number: positive or negative numbers with or without decimal place, or numbers written using exponential notation
String: represents textual data using 'single' or "double quotes"
Symbol: an anonymous, unique value
Variables Store Data Types
A variable is a place to store values and the main building block for all programming. When we write instructions for a computer to follow, we need to store small pieces of data in variables. JavaScript is a loosely typed language, which means you don't have to specify what type of information will be stored in a variable in advance.
You create a new variable by declaring it using the keywords var
, let
, or const
. I'll explain the difference between these keywords when we get to functions. Now, know that declaring a variable creates a statement, a single piece of code that accomplishes one task.
Dos and Don'ts for Naming Variables
Do start your variable name with a lowercase letter, dollar sign, or underscore
Do remember variables are case-sensitive
Do use names that describe the information the variable holds
Do use camelCase if your variable is made up of more than one word (capitalize the first letter of every word after the first word)
Don't start your variable name with a number
Don't use a dash, period, or space in the name
Don't use reserved words or keywords such as
var
in your variable name
*All of the Don'ts will throw an error!
Try it in your console!
Declare a variable. For example, typevar myVariableName
then hit return.
Now call the variable by typing its name and hitting return.
What is returned?
Until we assign a value to a variable, its value will be undefined. To assign a value to a variable, use the =
assignment operator. Remember, they are called variables because the stored data can vary each time a program is run. To reassign a value, use the variable name with the assignment operator.
Try it in your console!
Declare a new variable and assign it a value.
For example,var age = 1
Call the variable to confirm it holds the value you think it does. Reassign the value of the variable then call it again For example,age = 92
Combining Variables
Variables are flexible and powerful. Use descriptive names that help you to know what data type they contain. When we use variables together with different data types, type coercion can automatically convert values from one data type to another, such as numbers to strings. Take a look at the example and try it in your console.
In the example above, we used a +
as an operator to combine the values of two different variables with a string space. This is called concatenation. When we concatenate a number and a string, the number becomes part of a string. JavaScript is trying to help us by converting the number into a string so we can combine the two. We can concatenate more strings to make a sentence.
Another way to add values to strings is with template literals, special strings that allow us to interpolate information. They use backticks instead of "quotes" and a combination of a dollar sign $
followed by curly braces{}
. The backtick shares a key with ~ next to the number 1 on your keyboard. Interpolation is more readable than concatenation.
Statements vs Expressions
When we write JavaScript programs, we are writing scripts, a set of instructions for a computer to follow one by one. Each instruction is a statement. A statement acts but does not return anything. An expression is a statement that produces a value and can be written wherever a value is expected.
Statement Examples
true;
123;
"Hello, World";
var myVariable;
*Semicolons in JavaScript are optional after statements, but typically, it is best practice to include them.
Expression Examples
1 + 2
results in3
"Hello," + " World"
results in"Hello, World"
4
and 2 + 2
are both statements. 2 + 2
is also an expression that evaluates to 4
.
Hello Operator
Expressions rely on operators to produce a single value.
Here are 5 basic types of operators in JavaScript:
An assignment operator assigns a value to its left operand based on the value of its right operand. We used the simple assignment operator
=
to assign values to variables.Arithmetic operators perform basic math:
var addition = 2 + 2;
var subtraction = 2 - 2;
var multiplcation = 2 * 2;
var division = 2 / 2;
var exponentiation = 2**2;
var modulus = 5 % 2; // Remainder
The
+
operator can also be used as a string operator to concatenate or add strings.Comparison operators compare two values and return a Boolean value:
Strict equal returnstrue
if operands are equal and the same data type3 === 3
Greater than returnstrue
if the left operand is greater than the right operand4 > 2
Less than returnstrue
if the left operand is less than the right operand2 < 4
Logical operators combine expressions and return a Boolean value:
Logical AND&&
returns true if both operands are true.
Logical OR||
returns true if either operand is true.
Try using these operators in your console. You can read more about expressions and operators in the MDN Web Docs. I recommend this as your number-one resource for JavaScript questions!
Conditionals
In programs, we often want to perform an action based on a condition. "If this is true, then do that." We write conditionals similarly in JavaScript using expressions, operators, and statements.
This is the basic structure of an if/else
conditional:if ( expression ) { statement; } else { statement; }
The expression will usually contain an operator to make a comparison that evaluates to true or false. If the expression evaluates to true
, then the statement or statements for that condition will run. Otherwise (or else), if the expression is false
, then the statement or statements will not run at all. Take a look at the example and try it in your console.
You can also use else if
to specify a new condition to test if the first condition is false.
The console.log()
is a built-in function in JavaScript that prints any variables defined before or any message in the console.
Functions
We can also write our functions. A function is a predefined and reusable group of behavior. Functions group statements together to perform specific tasks. Like a variable, to create a function, you declare it with the JavaScript keyword function
and give it a descriptive name using camelCase. Since functions perform actions, naming them with an action verb is good practice. Right after the name, use opening and closing parentheses ()
.
function showFunctionParts() { statements; }
The parentheses are followed by a space and a pair of curly brackets {}
that hold the statements to run when the function is invoked. To invoke, also known as calling or running a function, you write the function's name with parentheses. You will see the function itself if you enter the function name without parentheses. Take a look at the example and try it in your console.
Passing Information to a Function
Sometimes, a function needs outside information to do its job. You give that function the information by providing parameters in the function declaration's parentheses. Parameters are placeholders that act like variables inside the function. When you invoke the function, you pass in arguments in place of the parameters. Take a look at the example and try it in your console.
The parameters for the addTwoNumbers function are num1 and num2. When you pass in more than one parameter, you separate them with commas. When we call the function, we replace the parameters with arguments. This function is performing a calculation. Why did it return undefined
instead of 3
? We need to use the keyword return
.
If there is no return statement, undefined
is returned instead. Return statements end function execution and specify a value to be returned to the function caller.
ES5 vs ES6
So far, we have looked at ES5 functions. ES5 refers to ECMAScript 2009, the first major revision to JavaScript. ECMAScript 2015, or ES6, was the second major revision to JavaScript, which introduced arrow functions. An arrow function is a compact alternative to traditional functions, but there are still use cases for ES5 functions, and there are differences and limitations to be aware of.
To write an arrow function, you declare it using a variable keyword followed by the function name, an assignment operator =
, parentheses (that can hold parameters) ()
, then an arrow made up of an equal and greater than symbol =>
. After the arrow is the statement body. Take a look at the example and try it in your console.
You invoke or run an ES6 arrow function like an ES5 function. You also use parameters and arguments in the parentheses in the same way.
One difference between ES5 and ES6 functions is that with arrow functions, you can have an explicit or implicit return. An explicit return is when a function returns values using the return
keyword. You must use an explicit return statement in a block body. A block is a chunk of code formed by curly braces {}
. An implicit return happens when a function returns values without using the return keyword. Implicit returns can only be used for functions with a single statement or expression.
ES6 also introduced let
and const
as additional keywords for declaring variables, as well as interpolation as an alternative to concatenation, which we already covered. Let's unpack the difference between var
, let
, and const
.
The additional variable declaration keywords were introduced to address scope issues associated with var
. Scope means where variables are available for use.
var
declarations are global when declared outside of a function. Global means that the variable is available for use in the whole program. When var
is used to declare a variable within a function, it has functional scope, meaning it is available and can be accessed only within that function. Misunderstanding the scope of your variables can cause a lot of bugs in your code, which is why let
and const
were introduced.
let
is now preferred for variable declarations because it is block-scoped. A variable declared let
is only available for use within the block of code bounded by {}
.
Like let
declarations, const
Declarations can only be accessed within the block where they were declared. The difference is that const
remains constant or the same within its scope. It cannot be updated or re-declared.
TL;DR
Data types, variables, and functions are the basic building blocks of JavaScript programming. If you want to learn JavaScript, start with a strong understanding of these key concepts.
Resources to keep learning
Eloquent JavaScript is a free ebook by Marijn Haverbeke with exercises at the end of each chapter.
JavaScript.com was built by Pluralsight for the JavaScript community, with resources for all levels of developers.
MDN web docs is an excellent resource covering Web platform technologies, including JavaScript, HTML, CSS, and Web APIs.
The Modern JavaScript Tutorial has detailed explanations on everything from the fundamentals to advanced topics.
Once you have the basics down, the Execute Program has a series of interactive lessons with built-in spaced repetition for developers to enhance and maintain their skills in JavaScript and TypeScript.
Google is every developer's best friend. Look up questions you have or concepts that don't make sense to you yet. There are many great written tutorials and videos to help you learn!
An article on how to learn to code with ChatGPT is coming soon...
Image by vectorjuice on Freepik