Just JavaScript - The Object Expression
Written by Ian Elliot   
Monday, 25 June 2018
Article Index
Just JavaScript - The Object Expression
Every Object Has a String Value
Type Conversion?

As in most programming languages, the expression is an important part of JavaScript, but it isn't quite the same. This is where the idea that JavaScript has some weird type conversions arises. But in reality JavaScript isn't too fussy about type and it doesn't really do conversions.

This is an extract from the book Just JavaScript by Ian Elliot.

Buy Now: from your local Amazon

Just JavaScript 
An Idiomatic Approach

JustJavaScriptSmall

A Radical Look At JavaScript

 

Most books on JavaScript either compare it to the better known class based languages such as Java or C++ and even go on to show you how to make it look like the one of these.

Just JavaScript is an experiment in telling JavaScript's story "just as it is" without trying to apologise for its lack of class or some other feature. The broad features of the story are very clear but some of the small details may need working out along the way - hence the use of the term "experiment". Read on, but don't assume that you are just reading an account of Java, C++ or C# translated to JavaScript - you need to think about things in a new way. 

Just JavaScript is a radical look at the language without apologies.

Contents

  1. JavaScript – Essentially Different
  2. In The Beginning Was The Object
  3. Real World Objects 
  4. The Function Object
          Extract - The Function Object
          Extract - Function Object Self Reference
  5. The Object Expression
  6. Function Scope, Lifetime & Closure
    Extract Scope, Lifetime & Closure
    Extract Execution Context ***NEW!
  7. Parameters, Returns and Destructuring
         Extract - Parameters, and Destructuring
  8. How Functions Become Methods
  9. Object Construction
         Extract: - Object Factories
  10. The Prototype
         Extract - ES2015 Class and Extends
  11. Inheritance and Type
  12. The Search For Type
  13. Property Checking

Buy Now: from your local Amazon

Also by Ian Elliot 
JavaScript Async: Events, Callbacks, Promises and Async Await
Just jQuery: The Core UI 
Just jQuery: Events, Async & AJAX  

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

Expressions form a mini-computer language inside most computer languages. The good news is that the way that they work is more or less the same in all languages. The symbols used for the operators change, the priorities change, and occasionally there are some additional operators.

An expression is essentially a generalization of the way arithmetic works. For standard arithmetic we only have four operators +, -, * and / standing in for the usual symbols for add, subtract, multiply and divide. These are all binary operators and take a value on the left and one on the right, the operands, and combine the two values to give a new value.

In this chapter we use some simple properties of JavaScript functions which are introduced in the next chapter.

Object Expressions

In programming languages, and in JavaScript in particular, there are generally a lot more operators than four, but they work in the same way taking two values and producing a new value.

In JavaScript you can think of a binary operator as taking two objects and producing a new object.

In many cases this distinction isn't important, but thinking in this way does make it easier to understand what is going on.

For example, take a careful look at:

var a=new Number(2);
a.myProperty="Hello World";
alert(a.myProperty);
a=a+1;
alert(a);
alert(a.myProperty);

What do you expect to see?

First we create a Number object with value 2 and a custom property myProperty. When you display the property it shows "Hello World" as you would expect. Next we add one to a and display its value, which is 3 as you would expect, but now the property is "undefined".

All we did was add one to a, surely this can't have modified the property?

It not only modified the property, it created a new object. When you add two Number objects together the result is a new Number object.

You can make this clearer by writing:

a=a+new Number(1);

and you will see that now the + operator takes the object referenced by a and the Number object we have created and adds their values together. As the result is a new object, it isn't surprising that it doesn't have the custom property you set on the first Number object.

JavaScript expressions combine objects and produce a final object.

This isn’t the way things are implemented in the JavaScript engine but this is more a matter of implementation detail than any deep philosophical approach.

Of course primitive values are operated on in their unwrapped non-object state in reality but for the sake of a good logical story we can ignore this as it makes no practical difference to how things behave. 

All Objects Have Value

In principle any operator in JavaScript can take two objects, any two objects, and produce a new Number, String or Boolean object. 

In JavaScript there are three important types of operator – those that produce Number objects, those that produce String objects and those that produce Boolean objects.

It turns out that the way Boolean operators work is different for various reasons.

For now let's just concentrate on Number and String operators.

The only String operator is concatenation which is represented by the same symbol as addition, +.

The main Number operators are +,-,* and /. Other Number operators work in similar ways so it is reasonable just to consider these four. 

You can use any object in an expression, not just Number and String.  For example:

myObject1+myObject2;

is perfectly valid irrespective of what the objects are.  

How can general objects be included in expressions? 

The answer to this question is that every JavaScript object has a value as returned by the valueOf method.

Methods are discussed in detail in Chapter 8 but for now you can treat a method as a property of an object that is used like a function.

The valueOf method is intended to return an object that is somehow regarded as the "value" of the object. 

Usually the value is a Number or a String but in fact it can be any object you care to return.

In practice, however, if it is going to be used with the standard operators it has to be a primitive object – i.e. a Number or a String.

When you use an object in an expression its valueOf method is automatically called to find a primitive value to use in the expression.

For example:

var myObject={};
myObject.valueOf=function(){return 1;};
var a=new Number(2);
a=a+myObject;
alert(a);

You can see that the  myObject's valueOf function returns 1.

You can also see that in:

a+myObject;

myObject behaves as if it had a value of 1, as you would expect.

In other words:

a+myObject;

is equivalent to:

a.valueOf()+myObject.valueOf()

Notice that when you write:

a+1;

you can think of this too as:

a.valueOf()+1.valueOf();

All operands in a string or numeric expression have an implied valueOf call to provide the primitive value used in the evaluation of the expression.

The Concatenation Operator

This simple picture is made more confusing by the way + is used to represent addition and String concatenation. 

How does JavaScript tell when you mean add and when you mean concatenate?

The rule is very simple. 

If either operand in: 

Object1 + Object2

returns a String from its valueOf method then the operator is String concatenation.  

For example:

var myObject1={};
myObject1.valueOf=function(){return "MyString1";}; var myObject2={};
myObject2.valueOf=function(){return "MyString2"};
a = myObject1 + myObject2;

In this case both valueOf methods return String objects and so the operator is concatenation and the result is:

MyString1MyString2

The same rule applies to the += operator which is concatenation if either a or b is a String in a+=b.

However, notice that a+=b is the same as a=a+(b) which is not always the same as a=a+b because b will be evaluated first. 

Now we come to the interesting question of what happens if only one of the two objects involved in the expression has a String value?

In this case by the rule we have just introduced the + is String concatenation but only one of the objects is a String.

The answer to this question is slightly more complicated than you might think – but very reasonable once you understand it.

But first a simple quiz.



Last Updated ( Monday, 25 June 2018 )