Going through a course on learning Javascript. The problem asks me to return my name as string. Here is an solution guide they've given me but I'm confused on what I'm missing. Here is what I have so far, but could use help on a step by step on how to solve it.
Guide :
describe("Solution", () => {
it("should return a string as a name", () => {
const name = getUserName();
if (typeof name === "string") {
console.log(`Hello, ${name}!`);
}
expect(name).to.be.a("string");
});
});
**my solution so far: **
function getUserName("Jawwad") {
let name = getUserName()
if (typeof name === String) {
console.log("Hello " + name);
}
return name;
}
I'm expecting it to return my name as string
A few problems with your logic:
You can't call a function inside of the same function.
It doesn't make sense to have a function receive as an argument the name it returns, for example: it would make sense to receive a name as argument and then do something with it like printing.
Here is an example derived from your code:
//innitial name
let theName = "Jonh"
// function purpose is to print the name
function printName(_theName) {
if (typeof _theName === 'string') { //string has to be in quotations
console.log("Hello " + _theName);
}
}
//calling function outside of itself
printName(theName);
Related
Please excuse how utterly "noobish" I am, I'm trying to learn as I go along but I'm very new.
I have the below code which I'm trying to use for a Discord bot. For the most part it works, however the # "ping" simply returns "#undefined" as opposed to the values I've set in the consts.
Would anyone be so kind as to point me in the right direction on this?
const ping = {
roleID: function() {
return this.role;
}
}
const John = {
role:"abc"
}
const Mary = {
role:"123"
}
function pingSubbed() {
let pingID = message.author.username;
if (pingID == "John") {
ping.roleID.call(John);
}
if (pingID == "Mary") {
ping.roleID.call(Mary);
}
}
yield hook.send(`**${message.author.username}**\n` + " " + messageContents + " " + "#"+pingSubbed());
I'm expecting the function pingSubbed() to determine the username of the person who posts in Discord, for example John, reference the above ping.roleID.call(John) and then take the appropriate role (in this case John = abc) and sending this information as a message itself - #123 - as in the last line "#"+pingSubbed()
You might find a look up table simpler to author and maintain:
function pingSubbed() {
let getId = Function.call.bind(ping.roleID);
return {
John: getId(John),
Mary: getId(Mary),
}[message.author.username] || ("Unknown User:"+message.author.username);
}
This puts a lot less boilerplate (even no quotes) in the way of your raw logic.
Even more jedi would be to make an iterable object containing your users instead of free-floating variables (well const(s)). This drastically simplifies the already-simpler look up table method:
const ping = {
roleID: function() {
return this.role;
}
}
const users={
John : {
role:"abc"
},
Mary: {
role:"123"
}
}
function pingSubbed() {
return ping.roleID.call(users[message.author.username]) ||
("Unknown User:"+message.author.username);
}
that gets it to the point of being almost all data with minimal logic and code to worry about...
The call inside your Object is working well you just forget to return the value that you need from your function
function pingSubbed() {
let pingID = message.author.username;
if (pingID == "John") {
ping.roleID.call(John);
}
if (pingID == "Mary") {
ping.roleID.call(Mary);
}
return pingID // add this line
}
When you use this keyword inside an object, it refers to the object itself.
I have a simple code to call a value from another function and its not working :
function ABC() {
var ID = XYZ(id);
Logger.log(ID); //throws error not defined.
}
function XYZ(id) {
var id = "1234"
return id;
}
What I wan to do is capture the value of id from function XYZ and Logger.log it into function ABC. But this reflects error.
Still not sure what you are trying to do with your code. This code is an "Impure Function" which is not recommended in JavaScript. How much I understood your code, below are my suggestions:
First
function abc() {
var id = xyz();
Logger.log(id);
}
function xyz() {
// Add whatever logic you want here to return ID value
var id = "1234"
return id;
}
Second
function abc() {
// Pass any value as an argument based on your requirement
var results = xyz('', '', '');
Logger.log(results.id);
Logger.log(results.name);
Logger.log(results.number);
}
function xyz(id, name, number) {
// Add whatever logic you want here
var newId = id || "1234";
var newName = name || "Mask";
var newNumber = number || "1234567890";
return { id: newId, name: newName, number: newNumber };
}
Based on what suits your requirement, you can take help of these codes.
Here you go -
function ABC() {
var ID = XYZ();
Logger.log(ID); // No longer throws the error :)
}
function XYZ() {
var id = "1234"
return id;
}
You do not need two functions, here is a simple function that will return the ID passed in.
const ABC = (id) => {
return id;
}
let a = ABC(122443);
console.log(a) // output 122443
For instance, if we have:
var greeting = "What is your name?";
var userName = prompt(greeting);
How would I take the string input from the user to pass along into a procedure? Just as a for instance, we will assume we're telling a story through the console. How would I take that STRING data from the user and pass it along into a function immediately following that?
Yes, I know it's remedial, but I am trying to get a grasp on core concepts.
var greeting = "What is your name?";
function getUserName() {
return prompt(greeting);
}
function yourFunction() {
alert("Hello "+getUserName());
}
yourFunction();
Example of how to use the prompt value:
var greeting = "What is your name?";
var userName = prompt(greeting);
if(testUserName(userName))
{
alert('name is abc');
}
else
{
alert('name isnt abc');
}
function testUserName(userName)
{
return userName == 'abc';
}
JSFiddle
The userName variable is defined at run time as the return value of the prompt and can be passed as a function parameter to be used when the JavaScript is parsed. This is true of almost all returned values and its not just limited to strings.
Example: http://jsfiddle.net/bradlilley/nGLTf/
var userName = prompt("What is your name?");
function foo(bar) {
if (bar && bar.length) {
console.log(bar);
return;
}
console.log('The prompt was left empty.');
return false;
};
foo(userName);
I was reading through fluent api I got a doubt.
I want to take in a string upon which a jQuery function or example is called upon
Function
function compareThis(newString) {
function compare(newString) {
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
}
}
Where it is called as
("alerting").compareThis("alerted").compare(); //alert 'different string'
I want to pass the data/string not as parameter but as called upon.
JSFiddle
Note: I would like to call the function in similar cases like finding date interval etc
You can use prototype to add function to String class:
String.prototype.compare = function(newString){
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
};
I think you should adapt the code for your function, but it's the idea.
Maybe I missed interpreted however, it looks as it you required a form of method chaining to compare string. To do this you can create a variable and create functions inside it.
var compare = (function(){
var thisString;
var stringToCompare;
var create = function(sVal) {
thisString = sVal;
return this;
};
// Public
var compareThis = function(sVal) {
stringToCompare = sVal;
return this;
};
var compare = function(anotherString) {
return thisString == stringToCompare;
};
return {
create: create,
compareThis: compareThis,
compare: compare
};
}());
var b = compare.create('test').compareThis('test').compare();
alert(b);
Example fiddle
I'm trying to create an object in JavaScript and I'm following Mozilla's tutorial . the tutorial works just fine, but when I apply that technique to my code it doesn't work. (I'm doing something wrong but I don't see it). I coded all my methods and I don't get any errors, I initialize my object and I don't get any errors either, I even call my methods and I don't get errors, but the return value is a string with my code instead of the value that I'm expecting
function JavaScriptObj(id, datatype) {
function initialize(id, datatype) {
if (typeof id === 'number' && id > 1) {
this.theID = id;
} else {
console.error("ERROR: JavaScriptObj.initialize" + id + "is NOT a valid argument");
}
if (typeof datatype === 'string') {
this.data_type = datatype;
} else {
console.error("ERROR: JavaScriptObj.initialize" + datatype + "is NOT a valid argument");
}
}
}
JavaScriptObj.prototype.getSectionName = function(){
var SectionName = "section-" + this.theID;
return SectionName;
};
var person2 = new JavaScriptObj(2, "texteditor");
alert(person2.getSectionName);
this is my jsfiddle
thanks in advance! :-)
Remove the initialize nested function:
function JavaScriptObj(id, datatype) {
if (typeof id === 'number' && id > 1) {
this.theID = id;
} else {
console.error("ERROR: JavaScriptObj: " + id + "is NOT a valid argument");
}
if (typeof datatype === 'string') {
this.data_type = datatype;
} else {
console.error("ERROR: JavaScriptObj: " + datatype + "is NOT a valid argument");
}
}
JavaScriptObj.prototype.getSectionName = function(){
var SectionName = "section-" + this.theID;
return SectionName;
};
var person2 = new JavaScriptObj(2, "texteditor");
alert(person2.getSectionName()); // need to call it too
It looks like you're not actually executing/calling your method. In order to call your method, you need to append parenthesis to the call:
alert(person2.getSectionName());
Small aside -- using console.log() instead of alert() tends to save you a few keystrokes and makes development a bit faster. Also, alert() is a blocking call that stops all other code execution on the page. While that won't make a difference when you're first starting out, it could potentially be a pain point down the road as your javascript ninja skills increase. :)