Introduction
Welcome to the JavaScript documentation! This lab will give you an introduction to operators.
This tutorial is from open-source community. Access the source code
Welcome to the JavaScript documentation! This lab will give you an introduction to operators.
Open the Terminal/SSH and type
node
to start practicing coding.
An operator
is a mathematical symbol that produces a result based on two values (or variables).
Add two numbers together or combine two strings.
// add two numbers together
6 + 9;
// add two strings together
"Hello " + "world!";
Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:
/*
Everything in between is a comment.
*/
If your comment contains no line breaks, it's an option to put it behind two slashes like this:
// This is a comment
These do what you'd expect them to do in basic math.
// Subtraction(-)
9 - 3;
// Multiplication(*)
8 * 2; // multiply in JS is an asterisk
// Division(/)
9 / 3;
As you've seen already: this assigns a value to a variable.
let myVariable = "Bob";
This performs a test to see if two values are equal and of the same data type. It returns a true
/false
(Boolean) result.
let myVariable = 3;
myVariable === 4;
This returns the logically opposite value of what it precedes. It turns a true
into a false
, etc.. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.
For "Not", the basic expression is true, but the comparison returns false
because we negate it:
// Not(!)
let myVariable = 3;
!(myVariable === 3);
"Does-not-equal" gives basically the same result with different syntax. Here we are testing "is myVariable
NOT equal to 3". This returns false
because myVariable
IS equal to 3:
// Does-not-equal(!==)
let myVariable = 3;
myVariable !== 3;
There are a lot more operators to explore, but this is enough for now. See Expressions and operators for a complete list.
Note: Mixing data types can lead to some strange results when performing calculations. Be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter
'35' + '25'
into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter35 + 25
you'll get the total of the two numbers.
Congratulations! You have completed the Operators lab. You can practice more labs in LabEx to improve your skills.