VBA->JS: Conditionals, Loops & Operators 1 (Syntax)

An important part of most programs we write is testing the values of variables and performing tasks based on the result. Typical VBA constructs that use comparisons are If, For, ForEach and Do…While. JavaScript provides the same functionality, using pretty much the same logic, but the syntax differs.

Before we look at these in the next post, however, it’s first important to learn what operator symbols JavaScript uses, how code blocks are defined and to understand the way the Equal sign ( = ) works.

Equal sign
In VBA the Equal sign is always used singularly:
strVariable = "string" or If x = 3 Then...
In JavaScript the equal sign can appear single, double or even triple! This takes some getting used to and, if your experience is similar to mine, you will on occasion forget to double or triple it up <sigh>

A single Equal sign is used to assign values to variables, just like in VBA:
var str = "value"; var y = 3;

To perform comparisons, however, at least two Equal signs are required:
if (str == "value")
This is the same as C# and those familiar with C# will tend to think they know how it works… But BEWARE when doing a Boolean comparison because JavaScript won’t always return True or False the way you’d expect if you use two Equal signs! Similarly to VBA, JavaScript plays fast and loose with data typing and will readily convert a string to a number. So testing
if(2=="2")
will evaluate to TRUE, just as in VBA. To ensure a strict comparison, use three Equal signs:
if(2==="2")
evaluates to false.

Code Blocks
Up until now, we’ve only looked at bits of code out-of-context: one or a few simple lines in order to compare VBA and JavaScript syntax. So before we get into discussing comparison syntax you first have to learn how JavaScript defines code blocks.
In VBA the start and end of code blocks come in expression pairs, such as Sub...End Sub, If...End If and For...Next.
JavaScript encloses code blocks in curly braces: { }. Curly braces always come in pairs – if one of a pair is missing then the code will not run correctly, just the same as in VBA. You’ll see the curly braces in action in the next post.

Comparison Operators
Some of the comparison operators are the same as in VBA, some are different. JavaScript uses the same ones as C# (with the mentioned exception of three equal signs for strict comparison).

VBA JS
= ==
===
Equals
< > !=
!==
Not equal
OR || Logical OR
AND && Logical AND
> > Greater than
< < Less than
>= >= Greater than or equal to
<= <= Less than or equal to


Leave a Reply