1

Refer to the code here below:

var fs = require('fs');
var file = 'test.js';
var search = new RegExp("\n", "g");

function printLineNum(err, fileContents) {
    if (err) return console.error(err.message);
    console.log("Total line(s) of document: %d", fileContents.match(search).length + 1);
}

fs.readFile(file, 'utf8', printLineNum);

// output: Total line(s) of document: 10

This is a working piece of code. But before I made the changes, line 7 looks like:

console.log("Total line(s) of document: " + fileContents.match(search).length + 1);
// output: 91

The unexpected error also can be solve by adding parenthesis to the numbers:

console.log("Total line(s) of document: " + (fileContents.match(search).length + 1));
// output: 10

I know how to avoid the error but I can't figure out what's wrong exactly. Is this a JavaScript thing or something to do with console.log?

0

2 Answers 2

4
console.log("Total line(s) of document: " + fileContents.match(search).length + 1);

In this instance the concatenation operator takes precedence over the addition operator and is evaluated first.

The statement will be evaluated like:

// string concatenation happens first
console.log((("string" + 9) + 1));
// resulting in more string concatenation 
console.log(("string9" + 1));
console.log("string91");
Sign up to request clarification or add additional context in comments.

1 Comment

"The concatenation operator has a higher precedence then the addition operator" - this is not correct. Try 1+2+"x".
4

This is due to the fact that the + operator is overloaded to perform both addition and string concatenation in JavaScript. If the type of either operand is a string then concatenation takes precedence.

This is described in the spec:

The addition operator either performs string concatenation or numeric addition.

The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:

  1. Let lref be the result of evaluating AdditiveExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating MultiplicativeExpression.
  4. Let rval be GetValue(rref).
  5. Let lprim be ToPrimitive(lval).
  6. Let rprim be ToPrimitive(rval).
  7. If Type(lprim) is String or Type(rprim) is String, then

    1. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
  8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.