1

I am coding a scientific calculator and I need some help:

function √(in){
    return Math.sqrt();
}
// throws an error
var √ = function(in){
    return Math.sqrt();
}
// also throws an error

var √ = "sqrt";
√randomSqNum = 100,
√random = {sqrt:4,cubert:8},
√sqNum = ["0","1","4","9","16","25"],
√null = null,
√undefined = undefined;

They all throw an error! Please explain why they throw an error. Also, Is there a way around this?

Joseph Goh
  • 376
  • 2
  • 13

3 Answers3

5

In Javascript, variable names must begin with a letter, _ or $. More information here:

http://www.w3schools.com/js/js_variables.asp

Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29
MHardwick
  • 659
  • 3
  • 9
3

You cannot use it directly as a name, but you can use it as key.

var f={}
f["√"] = Math.sqrt
alert(f["√"](5))

In such way you can define +-*/ and many other funcions.

f["+"] = function(a){
  return a.reduce(function(p,v){
    return p+v
  },0)
}

And when you have a parsed statement tree in form {o:fn,a:[s1,...,sn]} where fn is function name and s1,...,sn are subtrees or values, then you can simply get the result:

function calc(st){
  return (typeof st == 'object')?f[st.o].apply(null,st.a.map(calc)):st
}
Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29
3

JavaScript follows annex 31 of the unicode standard regarding identifier names.

I assume you are using U+221A as character. As you can see from the linked page, it can neither be used at the beginning of an identifier nor within it:

enter image description here

(likely because it is not even a letter).

Compare that to π, which is a letter and which can be used in an identifier name.

Also, Is there a way around this?

No. However, you can always try to find letters that look similar.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143