Swift – Random Numbers ”; Previous Next Random Numbers are the sequence of numbers that are generated by the system without any pre-defined pattern or in an unpredictable manner. They are commonly used in chance events, produce unpredictable outcomes, etc. Random numbers are widely used in cryptography, gaming, statistical analysis, generating unique id/sessions for users, etc. In Swift, we can find random numbers using the following methods − random(in:) function random(in: using:) function randomElement() function Using random(in:) Function We can find random numbers with the help of the random(in:) function. This function returns a random number from the given range. Using this function, we can generate random numbers of Int, Double, Float and Bool types. Syntax Following is the syntax of the random(in:) function − static func random(in: inputRange) Here this function takes only one parameter which is the inputRange. The inputRange represents a range in which a random() function creates a random number. Return Value This function returns a random number from the given range. Example Swift program to generate random numbers using random(in:) function. import Foundation // Generating a random number of Int type var randomNumber1 = Int.random(in: 10…23) print(“Random Number:”, randomNumber1) // Generating a random number of Float type var randomNumber2 = Float.random(in: 10.2…23.2) print(“Random Number:”, randomNumber2) // Generating a random number of Double type var randomNumber3 = Double.random(in: 15.2..<25.2) print(“Random Number:”, randomNumber3) // Generating a random number of Bool type var randomNumber4 = Bool.random() print(“Random Number:”, randomNumber4) Output It will produce the following output − Random Number: 20 Random Number: 14.4035845 Random Number: 17.450544998301993 Random Number: true Using random(in:using:) Function To generate random numbers Swift supports a pre-defined function named random(in:using:) function. This function generates a random number within the given range with the help of a given generator. It also generates random numbers of Int, Double, Float and Bool types. Syntax Following is the syntax of the random(in:using:) function − static func random(in: inputRange, using: generator) This function takes two parameters − inputRange − It represents a range. Its value must not be empty. generator − It represents the generator using which random(in:using:) function will generate a random number. Return Value This function returns a random number within the specified range. Example Swift program to generate random numbers using random(in:using:) function. import Foundation // Specifying a generator var myGenerator = SystemRandomNumberGenerator() // Generating a random number of Int type var randomNumber1 = Int.random(in: 30…43, using: &myGenerator) print(“Random Number:”, randomNumber1) // Generating a random number of Float type var randomNumber2 = Float.random(in: 12.2…33.2, using: &myGenerator) print(“Random Number:”, randomNumber2) // Generating a random number of Double type var randomNumber3 = Double.random(in: 35.2..<45.2, using: &myGenerator) print(“Random Number:”, randomNumber3) // Generating a random number of Bool type var randomNumber4 = Bool.random(using: &myGenerator) print(“Random Number:”, randomNumber4) Output It will produce the following output − Random Number: 34 Random Number: 20.267605 Random Number: 42.47363754282583 Random Number: false Using randomElement() Function When we are working with collections such as an array and dictionary, we can use the randomElement() function. This function returns a random element from the given collection. The value returned by this function is an optional type so we must unwrap it using (!). Syntax Following is the syntax of the randomElement() function − static func randomElement() Return Value This function returns a random number from the specified collection. If the collection is empty, then it will return nil. Example Swift program to generate a random element from the given collection. import Foundation let myVeggies = [“Lemon”, “Cabbage”, “Green Chilly”, “Potato”] // Getting random element let randomVeggie = myVeggies.randomElement()! print(“Random Element: (randomVeggie)”) Output It will produce the following output − Random Element: Lemon Print Page Previous Next Advertisements ”;
Category: Computer Programming
Swift – Discussion
Discuss Swift ”; Previous Next Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms. Print Page Previous Next Advertisements ”;
WebAssembly – Discussion
Discuss WebAssembly ”; Previous Next WebAssembly is a new programming language for the web. WebAssembly code is low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. Print Page Previous Next Advertisements ”;
Swift Opaque and Boxed Type
Swift – Opaque & Boxed Type ”; Previous Next Sometimes developers want to hide the details about the type. So Swift provides two special mechanisms named Opaque Types and Boxed Types. Using these two mechanisms we can manage and abstract the underlying details of types. The opaque type is used to hide the concrete type behind the protocols whereas the boxed type is used to wrap values in a container. Opaque Type The opaque type allows us to work with values of a specific type without showing the underlying concrete type. Or we can say that the opaque type is used to hide its return value type. It describes the return value in terms of the protocol it supports rather than showing the concrete type of the function’s return type. It preserves the type identity, which means the Swift compiler can access the type information but the user of the module cannot. It enhances the abstraction, encapsulation and modularity of the code by hiding the return type of the function or method and showing only the conforms to a certain protocol or structure. In Swift, we are allowed to use opaque return types with generics. Also if a function with opaque type is returned from multiple locations, then all the values returned by that function must have the same type. We can define opaque type using the some keyword along with the protocol or type. Syntax protocol ProtocolName { func methodName() -> String } func functionNAme() -> some ProtocolName { // Implementation that returns a type conforming to the given protocol} Example Swift program to demonstrate opaque type. // Function with return opaque type func randomElement() -> some Equatable{ Int.random(in: 0…14) } let elementOne = randomElement() let elementTwo = randomElement() // Now comparing the first and second elements returned by the function print(elementOne == elementTwo) Output It will produce the following output − false Example Swift program to demonstrate opaque type. // Define a protocol for shapes protocol Shape { func area() -> Double } // Implementing specific shapes struct Rectangle: Shape { let length: Double let breadth: Double func area() -> Double { return length * breadth } } struct Triangle: Shape { let length: Double let height: Double func area() -> Double { return ((length * height) / 2) } } // Function to add areas of two different shapes using opaque type func sumOfArea(rectShape: some Shape, triShape: some Shape) -> Double { return rectShape.area() + triShape.area() } let obj1 = Rectangle(length: 10.2, breadth: 11.0) let obj2 = Triangle(length: 5.1, height: 6.0) let totalArea = sumOfArea(rectShape: obj1, triShape: obj2) print(“Total Area is : (totalArea)”) Output It will produce the following output − Total Area is : 127.49999999999999 Boxed Protocol Type A boxed protocol type is used to warp a type that conforms to a protocol inside a container. It generally uses a generic type or existing type like “Any”. It allows us to work with values of different types that share a common protocol without showing the underlying types. Example Swift program to demonstrate opaque type. // Define a protocol protocol Display { func details() -> String } // Implementing for specific types struct Student: Display { var name: String func details() -> String { return “Student”s Name: (name)” } } struct Teacher: Display { var tname: String func details() -> String { return “Teacher”s Name: (tname)” } } // Wrapper type for boxed protocol struct BoxedDisplay { let x: Display init(_ x: Display) { self.x = x } } // Function that accepts a boxed protocol type func displayDetails(box: BoxedDisplay) { print(box.x.details()) } // Instances let obj1 = Student(name: “Monika”) let obj2 = Teacher(tname: “Mohit”) let box1 = BoxedDisplay(obj1) let box2 = BoxedDisplay(obj2) displayDetails(box: box1) displayDetails(box: box2) Output It will produce the following output − Student”s Name: Monika Teacher”s Name: Mohit Difference Between Opaque Type and Boxed Protocol Type Following are the major differences between opaque type and boxed protocol type − Opaque Type Boxed Protocol Type It uses some keyword to create opaque type. It uses wrapper type to create boxed protocol type. It allows function to hide its return type. It allows function to return a concrete type wrapped in a container. It provide type erasure. It may or may not have type erasure. It hides the concrete type. It warps the specific type. Print Page Previous Next Advertisements ”;
Swift – SwiftyJSON
Swift – SwiftyJSON ”; Previous Next What is JSON Data? JSON is known as JavaScript Object Notation. It is a lightweight and most commonly used data interchange format that is easy to read and write. It is generally used to transmit data between a server and an application. JSON data is generally represented in key-value pairs. For example − { “name”: “Monika”, “age”: 23, “city”: “Delhi” } Here name, age and city are the keys and Monika, 23 and Delhi are their respective values. In Swift, we can work with JSON data using the SwiftyJSON library. SwiftyJSON SwiftyJSON is a very important and powerful Swift library to handle JSON data in Swift programming language. It is commonly used to read and process JSON data returned by the APIs. It simplifies the process of parsing and working with JSON data in Swift easily by providing subscript syntax. It also provides various data types. Before SwiftyJSON the developer faced various problems while working with JSON data in Swift and the problems were − Verbose Syntax − Before the SwiftyJSON library the JSON data in Swift was handled by the JSONSerialization class which provides verbose syntaxes. Developers had to work with nested casting and a significant amount of optional unwrapping which makes code more complex and hard to read. Type Safety − While handling JSON data Swift doesn”t provide any direct way to handle optional values or nested structures in a type-safe manner. The user has to either use conditional casting or manually check the presence of keys. Readability − Reading and extracting values from the JSON was less readable. Swift doesn”t provide easy and clean syntax to work with JSON data. Error-handling − The developer had to use the do-catch block to handle errors manually because Swift does not provide any straightforward method to handle errors for JSON parsing and extracting. Lack of Convenience − Before SwiftyJSON developers had to write more boilerplate code to pars JSON data which makes the parsing more time-consuming. These issues are later solved by the SwiftJSON library. It provides more expressive and straightforward methods to deal with JSON data in Swift. How to use SwiftyJSON? To use the SwiftyJSON library in your project you have to follow the following steps − Step 1 − Install SwiftyJSON. To install SwiftyJSON you can use either CocoaPods or Swift Package Manager. Here we will use Swift Package Manager. So Open Xcode project → go to File → Swift Packages → Add Package Dependency and then enter the following SwiftyJSON GitHub repository URL − https://github.com/SwiftyJSON/SwiftyJSON.git Now follow the prompts to add the package. Step 2 − Now to use SwiftyJSON import the library at the top of the code using the import keyword. import SwiftyJSON Creating JSON Object: To create a JSON object SwiftyJSON provides the following initialiser. let object = JSON(data: dataObject) Or let obj = JSON(jsonObj) Accessing data − You can use subscripts to access JSON data. // Getting string from JSON dictionary let stdName = json[“name”].stringValue // Getting int from JSON array let value = json[1].int= Iterating over an array or dictionary − SwiftyJSON supports a for-in loop to iterate over the elements of an array or dictionary. // For array for(index, element):(String, JSON) in json{ Write something } // For dictionary for(key, element):(String, JSON) in json{ Write something } Example import SwiftyJSON // JSON string let inputJsonString = “”” { “name”: “Mohan”, “age”: 40, “branch”: “CSE” }””” if let jsonObj = inputJsonString.data(using: .utf8) { let x = try? JSON(data: jsonObj) // Accessing values using SwiftyJSON subscript syntax let name = x?[“name”].stringValue let age = x?[“age”].intValue let branch = x?[“branch”].stringValue // Perform operations print(“Name: (name ?? “N/A”)”) print(“Age: (age ?? 0)”) print(“Branch: (branch ?? “N/A”)”) } Output This code will work on Xcode. It will not work on an online Swift compiler. − Name: Mohan Age: 40 Branch: CSE Print Page Previous Next Advertisements ”;
Swift – for in loop
Swift – for-in Loop ”; Previous Next Swift for-in Loop The for-in loop iterates over collections of elements, such as ranges arrays, sets, dictionaries, etc. It iterates through each element of the specified collection without any explicit index manipulation. It is the most commonly used control flow statement because it expresses logic in a very clean and readable way. It is also compatible with functional programming, which means you can easily use high-order functions like filter(), map(), reduce, etc with a for-in loop. Syntax Following is the syntax of the for-in loop − for index in var{ Statement(s) } Flow Diagram The following flow diagram will show how the for-in loop works − Example Swift program to demonstrate the use of for-in loop. import Foundation var someInts:[Int] = [10, 20, 30] for index in someInts { print( “Value of index is (index)”) } Output It will produce the following output − Value of index is 10 Value of index is 20 Value of index is 30 Swift for-in Loop with Underscore “_” In a for-in loop, we can also ignore values from the given collection with the help of underscore “_”. Here we use underscore “_” in place of variable Name in the for-in loop. It will ignore the current value while iterating. It is commonly used when we only want to iterate a given number of times and does not require the value from the collection. Syntax Following is the syntax of the for-in loop with underscore − for _ in var{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with underscore. import Foundation let numbers = [3, 5, 76, 12, 4] // Using the underscore to ignore the values for _ in numbers { // Following code will execute in each iteration print(“Hello!! for-in loop!”) } Output It will produce the following output − Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Swift for-in Loop with Ranges We can also use range with a for-in loop. A range is the easiest way to represent a range of values in the for-in loop, it can be open, closed or half-open. The for-in loop iterates over each value in the given range and in each iteration, the loop variable takes the value of the current element in the range. Syntax Following is the syntax of the for-in loop with range − // With a closed range for variableName in start…end{ Statement(s) } // With half-open range for variableName in start..<end{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with range. import Foundation // Using closed Range print(“Loop 1:”) for x in 1…6 { print(x) } // Using half-open Range print(“Loop 2:”) for y in 1..<6 { print(y) } Output It will produce the following output − Loop 1: 1 2 3 4 5 6 Loop 2: 1 2 3 4 5 Swift for-in Loop with stride() Function We can use the stride() function with a for-in loop. The stride() function iterates over a range of values with a specific step between them. It is generally used to achieve more complex iteration patterns or can create a loop with a customized iteration pattern. Syntax Following is the syntax of the for-in loop with stride() function − for variableName in stride(from: value, to: value, by: value){ statement(s) } Parameters The stride() function takes three parameters − from − It contains the starting value of the range. to − It contains the end value of the range. Its value does not include. by − It contains the number of steps or strides between the values. If its value is positive, then the stride iterates in an upward direction or if the value is negative, then the stride iterates in the downward direction. Example Swift program to demonstrate how to use for-in loop with stride() function. import Foundation // The stride() function moves in upward direction print(“Loop 1:”) for x in stride(from: 1, to: 7, by: 2) { print(x) } // The stride() function moves in downward direction print(“nLoop 2:”) for y in stride(from: 7, to: 1, by: -2) { print(y) } Output It will produce the following output − Loop 1: 1 3 5 Loop 2: 7 5 3 Swift for-in Loop with where Clause Swift also provides a where clause which we can use with a for-in loop. A where clause is used to filter out only those elements that satisfy the condition specified in the where clause from the given collection. It can work with all iterable collections such as arrays, sets, and dictionaries. Syntax Following is the syntax of the for-in loop with where clause − for variableName in collectionName where condition{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with where clause. import Foundation let nums = [43, 23, 66, 12, 2, 45, 33] // Using the where clause to filter out only even elements from the array for n in nums where n % 2 == 0 { print(“Even number is (n)”) } Output It will produce the following output − Even number is 66 Even number is 12 Even number is 2 Print Page Previous Next Advertisements ”;
WebAssembly – Examples
WebAssembly – Examples ”; Previous Next The chapter discusses the examples with regards to WebAssembly. Example 1 Following is the example of C Program to get the max Element − void displaylog(int n); /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; displaylog(result); return result; } Compile the code in wasm fiddle and download the .wasm and .wat code. Wat code The Wat code is as follows − (module (type $FUNCSIG$vi (func (param i32))) (import “env” “displaylog” (func $displaylog (param i32))) (table 0 anyfunc) (memory $0 1) (export “memory” (memory $0)) (export “max” (func $max)) (func $max (; 1 😉 (param $0 i32) (param $1 i32) (result i32) (call $displaylog (tee_local $0 (select (get_local $0) (get_local $1) (i32.gt_s (get_local $0) (get_local $1)) ) ) ) (get_local $0) ) ) Download .wasm code and let us use in the .html file as shown below − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> </head> <body> <script> const importObj = { env: { displaylog: n => alert(“The max of (400, 130) is ” +n) } }; fetch(“testmax.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.max(400,130)); }); </script> </body> </html> Output The output is as follows − Example 2 Following is the C++ code to get the fibonacci series of given number. #include <iostream>> void displaylog(int n); int fibonacciSeries(int number) { int n1=0,n2=1,n3,i; for(i=2;i<number;++i) { n3=n1+n2; displaylog(n); n1=n2; n2=n3; } return 0; } I am using wasm explorer to compile the code. Download Wat and Wasm and test the same in the browser. You can use the below mentioned code − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> </head> <body> <script> const importObj = { env: { _Z10displaylogi: n => console.log(n) } }; fetch(“fib.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports._Z15fibonacciSeriesi(10)); }); </script> </body> </html> Output The output is as follows − Example 3 Following is the Rust code to add elements in a given array. fn add_array(x: i32) -> i32 { let mut sum = 0; let mut numbers = [10,20,30]; for i in 0..3 { sum += numbers[i]; } sum } We are going to make use of WebAssembly Studio to compile RUST to wasm. Build the code and download the wasm file and execute the same in the browser. <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> </head> <body> <script> const importObj = { env: { } }; fetch(“add_array.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.add_array()); }); </script> </body> </html> Output The output will be as given below − Print Page Previous Next Advertisements ”;
WebAssembly – Working with C
WebAssembly – Working with C ”; Previous Next In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser. For Example − C Program #include<stdio.h> int square(int n) { return n*n; } We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c. We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code. Compile test.c in your command prompt as shown below − emcc square.c -s STANDALONE_WASM –o findsquare.wasm emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file. Example − findsquare.html <!doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Square function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id=”textcontent”></div> <script> let square; fetch(“findsquare.wasm”).then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { square = instance.exports.square(13); console.log(“The square of 13 = ” +square); document.getElementById(“textcontent”).innerHTML = “The square of 13 = ” +square; }); </script> </body> </html> Output The output is as mentioned below − Print Page Previous Next Advertisements ”;
Swift – if statement
Swift – If Statement ”; Previous Next An if statement consists of a Boolean expression followed by a block of statements. When the boolean expression is true, then only the block of statements will execute. Otherwise, the controls move to the next statement present just after the if statement block. They are also known as branch statements because they allow the program to take different paths according to the given condition. For example, a teacher says to its students that “they are only allowed to write with a black pencil”. So here the conditional statement is “black pencil”. Hence If the “black pencil = true”, then only students are allowed to write. Syntax Following is the syntax of the if statement − if boolean_expression{ /* statement(s) will execute if the boolean expression is true */ } If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. Flow Diagram The following flow diagram will show how if-statement works − Example Swift program to check if the given number is less than 20 or not using the if statement. import Foundation var varA:Int = 10; /* Check the boolean condition using the if statement */ if varA < 20 { /* If the condition is true then print the following */ print(“varA is less than 20”); } print(“Value of variable varA is (varA)”); Output It will produce the following output − varA is less than 20 The value of variable varA is 10 Example Swift program to find the age for voting using if statement. import Foundation var age : Int = 19; /* Checking the age for voting */ if age >= 18 { /* If the condition is true */ print(“Eligible for voting”); } print(“A Candidate whose age is 18+ is eligible for voting “) Output It will produce the following output − Eligible for voting A candidate whose age is 18+ is eligible for voting Example Swift program to check the entered username is equal to the stored username using if statement. import Foundation let username = “input231″ let inputUsername = “input231″ // Checking for equality if username == inputUsername{ print(“Login successful”) } var result = 32 + 23 print(result) Output It will produce the following output − Login successful 55 Print Page Previous Next Advertisements ”;
WebAssembly – “Hello World”
WebAssembly – “Hello World” ”; Previous Next In this chapter we are going to write a simple program in C and convert it into .wasm and execute the same in the browser to get the text “Hello World”. Will make use of wasm explorer tool that will convert the C program to .wasm and will make use of the .wasm inside our .html file. The Wasm explorer tool which is available at https://mbebenita.github.io/WasmExplorer/ looks as follows − The C code that we are going to use is as follows − #include <stdio.h> char *c_hello() { return “Hello World”; } Update the first block in wasm explorer with the C code as shown below − Click on COMPILE Button to compile to WASM and WAT and Firefox x86 Web Assembly as shown below − Use the DOWNLOAD to get the .wasm file and save it as firstprog.wasm. Create a .html file called firstprog.html as shown below − <!doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Hello World</title> </head> <body> <div id=”textcontent”></div> <script type=”text/javascript”> //Your code from webassembly here </script> </body> </html> Let us now use firstprog.wasm to read the helloworld from the C function c_hello(). Step 1 Use fetch() api to read the firstprog.wasm code. Step 2 The .wasm code has to be converted into arraybuffer by using ArrayBuffer. The ArrayBuffer object will return you a fixed length binary data buffer. The code so far will be as follows − <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) </script> Step 3 The bytes from ArrayBuffer have to be compiled into a module by using WebAssembly.compile(buffer) function. The code will look like below − <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) </script> Step 4 To get the module we have to call the webassembly.instance constructor as shown below − <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) </script> Step 5 Let us now console the instance to see the details in the browser. <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { console.log(instance); }); </script> The console.log details are shown below − To get the string “Hello World” from the function c_hello(), we need to add some code in javascript. First, get the memory buffer details as shown below − let buffer = instance.exports.memory.buffer;; The buffer value has to be converted to a typed array so that we can read the values from it. The buffer has the string Hello World in it. To convert to typed call the constructor Uint8Array as shown below − let buffer = new Uint8Array(instance.exports.memory.buffer); Now, we can read the value from the buffer in a for – loop. Let us now get the start point to read the buffer, by calling the function we wrote as shown below − let test = instance.exports.c_hello(); Now, the test variable has the start point to read our string. WebAssembly does not have anything for string values, everything is stored as integers. So when, we read the value from the buffer, they will be an integer value and we need to convert it into a string using fromCharCode() in javascript. The code is as follows − let mytext = “”; for (let i=test; buffer[i]; i++){ mytext += String.fromCharCode(buffer[i]); } Now, when you console mytext you should see the string “Hello World”. Example The complete code is as follows − <!doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Add Function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id=”textcontent”></div> <script> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module)}) .then(instance => { console.log(instance); let buffer = new Uint8Array(instance.exports.memory.buffer); let test = instance.exports.c_hello(); let mytext = “”; for (let i=test; buffer[i]; i++) { mytext += String.fromCharCode(buffer[i]); } console.log(mytext); document.getElementById(“textcontent”).innerHTML = mytext; }); </script> </body> </html> We have added a div and the content is added to the div, so the string is displayed on the browser. Output The output is mentioned below − Print Page Previous Next Advertisements ”;